插入遍历时ActiveRecord一对多更新错误

时间:2014-12-22 13:40:26

标签: ruby 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的更多信息 有谁知道为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以在阅读书籍之前更新ActiveRecord :: Relation for User。

尝试在user.reload之后添加book.save

点击here以获取更多信息。