在模型回调条件中使用 self.attribute 和属性有什么区别吗?



使用 self.attribute_changed 或attribute_changed回调添加条件有什么区别吗?

class PlayEvent < ActiveRecord::Base
... 
after_save :update_next_event_at!, if: 'self.event_at_changed?'
after_save :update_next_event_at!, if: 'event_at_changed?'
...    
end

首选使用哪一个?

没有区别,不需要self.

您唯一需要self.的时间是在任务中。 如果您有模型属性comment和类似...

def update_comment
comment = "this is the new comment"
end

这可能不是您所期望的,因为在这种情况下,赋值会创建一个变量comment该变量是该方法的本地变量。 Rubocop 将此标识为无用的赋值,因为comment变量随后不会在任何地方使用。

然而。。。

def update_comment
self.comment = "this is the new comment"
end

将正确更改记录属性。

最新更新