Adam Bronfin
Adam Bronfin

Reputation: 1279

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 = "[email protected]"
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

Upvotes: 0

Views: 110

Answers (2)

Akshay Borade
Akshay Borade

Reputation: 2472

user1 = User.new
user1.email = "[email protected]"
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

Upvotes: 1

Anthony
Anthony

Reputation: 15967

The problem is your user does not have an id by the time you're trying to make associations on it. Just a quick update to the script and you should be good to go:

user1 = User.create(email: "[email protected]", name: "testname", password: "password")
user1.library.create
user1.library.books.create(hash_of_attributes)

Upvotes: 0

Related Questions