0
給定兩個ActiveRecord的車型更新錯誤:ActiveRecord的一對許多當一一對多關聯, User.rb插入一個遍歷
class User < ActiveRecord::Base
has_many :books, foreign_key: "user_id", dependent: :destroy
end
Book.rb:
class Book < ActiveRecord::Base
belongs_to :user, foreign_key: "user_id", dependent: :destroy
end
然後在app.rb中,問題就會出現
class ProblemApp
dbconfig = YAML.load(File.open("config/database.yml").read)
ActiveRecord::Base.establish_connection(dbconfig['development'])
user = User.first
(1..5).each do |price|
user.books.each do |book| ####### bug line !!!!!!!!!!!!!!!
end ####### bug line !!!!!!!!!!!!!!!
return nil unless (book = user.books.find_by_id 1)
puts book.name.to_s + " + " + price.to_s
book.price = price # change attr
puts book.save # save changing
book = user.books.first
puts book.name.to_s + " - " + book.price.to_s
puts "================="
end
end
控制檯輸出:
Running...
Ruby + 1
true
Ruby - 1
=================
Ruby + 2
true
Ruby - 1
=================
Ruby + 3
true
Ruby - 1
=================
Ruby + 4
true
Ruby - 1
=================
Ruby + 5
true
Ruby - 1
=================
在每次更改操作前插入books.each塊時,模型的價格不會更新。但是,執行保存行時,數據庫中的價格可能會更新。當刪除塊的兩行時,問題消失。
更多信息在my github 有人知道爲什麼以及如何解決這個問題?
看來'reload'''方法現在是最好的解決方案。我可以使用'''user.books.reload'''來更新書籍字段,但是整個'''user'''。非常感謝。 – SanCoder