Rake db:seed 没有将创建的对象正确关联到它的父模型?

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

我有一个用户模型 has_one 图书馆 has_many 书籍。

在我的种子文件中,我这样做了:

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!

行 puts "book1 library_id " + book1.library_id.to_s 清楚地输出值 1,因此我们知道 library_id 属性在新创建的 Book 模型上设置为 1。

但是,在 运行 rake db:seed 之后,我 运行 rails 控制台并执行:

User.first.library.books

才发现

<ActiveRecord::Associations::CollectionProxy []>

和运行宁Book.first显示

 library_id: nil

所以这本书是创建的,只是它没有正确关联到我的图书馆,而我的图书馆正确关联到我的用户模型。

这是怎么回事?

运行 Rails 4.1.6

问题是当您尝试建立关联时,您的用户还没有 ID。只需快速更新脚本,您就可以开始了:

user1 = User.create(email: "test@email.com", name: "testname", password: "password")
user1.library.create
user1.library.books.create(hash_of_attributes)
user1 = User.new
user1.email = "test@email.com"
user1.name  = "testname"
user1.password = "password"
user1.save!

首先你需要保存用户的id。那么....

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