I have three models, Account, User and Contact:
class User < ActiveRecord::Base
has_one :account
has_many :contacts, :through => :account
end
class Account < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
has_many :contacts
end
class Contact < ActiveRecord::Base
belongs_to :account
end
I’m trying to scope build a new contact through the user record, like this in my contacts controller.
def create
@contact = current_user.contacts.build(params[:contact])
respond_to do |format|
if @contact.save
...
else
...
end
end
end
When I do this, I don’t receive any errors, the contact record is saved to the database however the account_id column is not set on the contact, and it is not added to the collection so calling @current_user.contacts returns an empty collection.
Any suggestions?
Using
buildmakes a new instance of Contact in memory, but you would need to manually set theaccount_idon the record (e.g.@contact.account_id = current_user.account.id), or perhaps set it in a hidden field in thenewform used to display the contact for creation such that it is picked up in the params array passed to thebuildmethod.You might also want to consider whether
accepts_nested_attributes_formay be helpful in this case. Another option may be to usedelegate, although in both cases, your use may be sort of the opposite of what these are intended for (typically defined on the “parent”).Update:
In your case, the
buildmethod is added to both the User instance and to the Account (maybe “Owner”) instance, because you have both a many-to-many relationship between User and Contact, as well as a one-to-many relationship between Account and Contact. So to get theaccount_idI think you would need to call Account’s build, likeDoes this work?