Search code examples
ruby-on-railsrubyassociationshas-manyhas-one

Rails has_one vs has_many association


I've a model say Book and another model named say Title. The associations are simply defined below.

class Book < ApplicationRecord
    has_one :title
end

class Title < ApplicationRecord
    belongs_to :book
end

Now, if I generate a schema with a foreign key of book_id in Title and create a new record for Book, I am not being able to create a new Title record via book.title.create! as book.title returns nil.

But, if I change the association to

 class Book < ApplicationRecord
    has_many :titles
 end

then I am clearly able to create a new Title record using book.title.create!. So, what I have to do to make it work with the has_one association is do something like book.title = Title.create!(foo: "bar", book_id: book.id).

When I checked the values for book.title in the latter case, the console returns <ActiveRecord::Associations::CollectionProxy []> but for the former, book.title returns nil and hence the NoMethod Error for nil class.

I tried following the official docs and some other posts in stack regarding this. But somehow, its still unclear to me.


Solution

  • The reason of this behaviour is that Rails creates methods in a form of create_#{association_name} for every has_one association_name. There are docs for this, if you need extra information.

    Thus, to create a title for a book, you'll need something like:

    book.create_title
    

    It will perform the trick, you're expecting