在 before_update 回调中更改属性值

Fel*_*ger 0 ruby-on-rails callback ruby-on-rails-4

当我检测到已更改且即将更新时,我尝试更改attribute_1值。attribute_2

对象已更新,但设置的attribute_1值并未持续存在,为什么?

before_update :check_attribute2_change

def check_attribute_2_change
  if attribute_2_changed?
      attribute_1 = nil
  end
end
Run Code Online (Sandbox Code Playgroud)

Aad*_*ain 6

尝试这个:

before_update :check_attribute2_change

def check_attribute_2_change
  self.attribute_1 = nil if attribute_2_changed?      
end
Run Code Online (Sandbox Code Playgroud)

  • 我不知道“自我”如此重要。 (2认同)
  • 这里的 self 很重要,它表明 attribute_1 实际上是您所引用的实例对象的属性。如果没有“self”,它将“attribute_1”作为变量,因此您看不到结果。希望能澄清原因:) (2认同)