Create on a has_many through?


#1

Hi, I have two models, User and Item, as well as a join model,
UserItem. So the User model includes the lines:

has_many :user_items
has_many :items, :through => :user_items

I’ve noticed that this doesn’t work:

u = User.new
u.items.create :name => “hammer”

Any reason why? Seems like it would be a nice feature. To get around
it, I usually do this:

u.items << Item.create :name => “hammer”
or
u.user_items.create(:item => User.create(:name => “hammer”))

Thanks for your time,

Andrew


#2

removed_email_address@domain.invalid wrote:

Hi, I have two models, User and Item, as well as a join model,
UserItem. So the User model includes the lines:

has_many :user_items
has_many :items, :through => :user_items

I’ve noticed that this doesn’t work:

u = User.new
u.items.create :name => “hammer”

Any reason why? Seems like it would be a nice feature. To get around
it, I usually do this:

u.items << Item.create :name => “hammer”
or
u.user_items.create(:item => User.create(:name => “hammer”))

You can’t do that with create, but create! will do what you want.


Josh S.
http://blog.hasmanythrough.com


#3

The reason this does not work is because your user object does not
exist in the database yet and there is no id to create the
association. either create or save the user first.

see the docs on why

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000642