Forum: Ruby on Rails Correct way to build an AR object with multiple associations?

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.
Lisa Klein (Guest)
on 2008-12-18 09:49
(Received via mailing list)
I have a Book resource that belongs both to a User and to an Isbn.
What is the recommended way of building a new Book record in this type
of situation?

class Book < ActiveRecord::Base
  belongs_to :user
  belongs_to :isbn
end

Currently I'm doing the following:

@isbn = Isbn.find(...)
book = @isbn.books.build(...)
book.user_id = @user.id
book.save

Is this the way it's supposed to be done?  I know that it's preferred
to interact with dependent resources through their associations. So
adding the user_id manually seems a bit clunky to me.  But I'm not
sure how else to do it!

Thanks in advance.
Andrew P. (Guest)
on 2008-12-18 12:00
(Received via mailing list)
Lisa Klein wrote:
> book.user_id = @user.id
>
> Is this the way it's supposed to be done?  I know that it's preferred
> to interact with dependent resources through their associations. So
> adding the user_id manually seems a bit clunky to me.  But I'm not
>

Do

book.user = @user

instead then (ultimately it's the same thing obviously).
Lisa Klein (Guest)
on 2008-12-18 15:38
(Received via mailing list)
Oooh, that clarified a few things.  Thanks Andrew!
This topic is locked and can not be replied to.