Rails 5.2 的简化代码。
一个非常简单的Base
类,它添加了其Items的一些值。
class Base < ApplicationRecord
has_many :items
def values
children.map(&:value).sum
end
end
修改自身的 Item
类:
class Item < ApplicationRecord
belongs_to: :base
def increment
puts parent.values # == 0
self.value = 10
save!
puts parent.values # == 0 #???
end
end
当调用some_item.increment
时,我希望第二个parent.values
返回10,但事实并非如此。
在下一次调用时,它确实返回 10,不知何故,它被缓存以供第一次调用。
是否存在某种隐藏的缓存机制,或者 save!
是否延迟了更改?
最佳答案
您必须使用reload!
重新加载父对象
class Item < ApplicationRecord
belongs_to: :base
def increment
puts parent.values # == 0
self.value = 10
save!
parent.reload!
puts parent.values
end
end
关于ruby-on-rails - 保存后,父级的 Rails has_many 关系未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58411434/