Search code examples
ruby-on-railsrubyactiverecordrake

Rake db:seed not associating a created object to it's parent model correctly?


I have a User model which has_one Library which has_many Books.

In my seeds file I do this:

user1 = User.new
user1.email = "test@email.com"
user1.name  = "testname"
user1.password = "password"
user1.library = Library.new
user1.library.save!
book1 = Book.create!(hash_of_attributes)
user1.library.books << book1
puts "book1 library_id " + book1.library_id.to_s
user1.save!

the line puts "book1 library_id " + book1.library_id.to_s clearly outputs the value of 1, so we know the library_id attribute is set to 1 on the newly created Book model.

However, after running rake db:seed, I run rails console and do:

User.first.library.books

only to find

<ActiveRecord::Associations::CollectionProxy []>

And running Book.first shows

 library_id: nil

So the book was created except it wasn't properly associated to my library, which is properly associated to my user model.

What is going on?

Running Rails 4.1.6


Solution

  • user1 = User.new
    user1.email = "test@email.com"
    user1.name  = "testname"
    user1.password = "password"
    user1.save!
    

    First of all you need to save user for it's id. Then ....

    user1.library = Library.new
    library1 = user1.library.save!
    
    book = Book.create!(hash_of_attributes)
    book1 = library1.books << book
    puts "book1 library_id " + book1.library_id.to_s