Forum: Ruby on Rails create on a has_many through?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
(Guest)
on 2007-03-01 00:28
(Received via mailing list)
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
Josh S. (Guest)
on 2007-03-01 01:30
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
Chris H. (Guest)
on 2007-03-01 16:06
(Received via mailing list)
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/As...
This topic is locked and can not be replied to.