Create on a has_many through?

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

[email protected] 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

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs