1

I have two model's Contact, and User. When I create a new user I am trying to create the contact at the same time. But It is not getting created for some reason. Any ideas on why?

class Contact
  include Mongoid::Document
  include Mongoid::Timestamps
  include Mongoid::MultiParameterAttributes
  include Mongoid::Paranoia
  include Mongoid::Versioning

  # Attr.
  attr_accessible :first_name, :last_name, :birthday, :email_addresses_attributes, :phone_numbers_attributes, :relationships_attributes, :addresses_attributes

  #Relationships
  belongs_to :firm, validate: true
  has_one :user # contact information for user
  has_many :relationships, autosave: true
  has_many :clients
  has_many :notes, dependent: :destroy
  ...
end


class User
  include Mongoid::Document
  include ActiveModel::SecurePassword
  include Mongoid::Timestamps

  # Attr.
  attr_accessible :contact_id, :contact_attributes, :password, :password_confirmation, :google_tokens

  #Relationships
  belongs_to :firm, validate: true
  belongs_to :contact, validate: true, autosave: true
  has_one :user_type
  embeds_many :histories

  # Nested Attrs
  accepts_nested_attributes_for :contact
  ...
end
Jason Waldrip
  • 5,038
  • 8
  • 36
  • 59

1 Answers1

0

accepts_nested_attributes_for is done on the owner object to allow you to set attributes of objects that belong it.

In your case, User belongs to (or is nested under) Contact. You would have to do accepts_nested_attributes_for :user in your Contact model.

You could switch it around so that User has_one :contact and Contact belongs_to :user. This requires you give Contact a user_id field.

tybro0103
  • 48,327
  • 33
  • 144
  • 170
  • Yes but I am creating the User not the contact. I tried adding the accepts_nested_attributes_for :user to the Contact model with no luck. Unfortunately if I switch things around then it breaks my forms. My form error says that the user_id is missing, if I added a user_id field how would that populate? – Jason Waldrip Mar 19 '12 at 20:42
  • If the main object in your form is the User then you'll want to switch the relationship. Just add a user_id field to Contact. It'll get populated when your form submits. – tybro0103 Mar 19 '12 at 21:33
  • still no luck. I made the tweaks and the contact is still not saving. – Jason Waldrip Mar 19 '12 at 21:59
  • I actually built an app pulled out of my master. No views but you can test with the params string in the readme. https://github.com/jwaldrip/Example-App – Jason Waldrip Mar 20 '12 at 01:28