Rake db:seed没有正确地将创建的对象与其父模型相关联?

时间:2015-05-24 23:40:52

标签: ruby-on-rails ruby activerecord rake

我有一个用户模型,其中has_one Library has_many Books。

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

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!

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

然而,在运行rake db:seed之后,我运行rails console并执行:

User.first.library.books

只找到

<ActiveRecord::Associations::CollectionProxy []>

运行Book.first显示

 library_id: nil

所以这本书被创建了,除了它与我的库没有正确关联,它与我的用户模型正确关联。

发生了什么事?

运行Rails 4.1.6

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

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

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