保存后未更新父级的rails has_many关系

时间:2019-10-16 10:43:29

标签: ruby-on-rails activerecord

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!延迟了更改?

1 个答案:

答案 0 :(得分:2)

您必须使用$string = 'my-css-class-1 { background: rgba(0, 0, 0, 0.12); text-decoration: none;} my-css-class-2 {background: rgba(234, 56, 49, 0.4); text-decoration: none; }'; $replace = preg_replace('/([0-9]+),([0-9]+),([0-9]+),([.0-9]+)/', '$1, $2, $3, 1', $string); echo $replace;

重新加载父对象
reload!