Correct way to build an AR object with multiple associations?


#1

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.


#2

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).


#3

Oooh, that clarified a few things. Thanks Andrew!