在我的rails 模型中,我有一个名为employer_wcb 的十进制属性。如果在更改雇主 wcb 时将脏位设置为 true,我希望它。我想覆盖employer_wcb setter 方法。有什么办法(特别是使用元编程)?
问问题
959 次
2 回答
8
所以实际上,从 Rails v2.1 开始,这已被融入到 Rails 中。查看ActiveRecord::Dirty的文档。总之:
# Create a new Thing model instance;
# Dirty bit should be unset...
t = Thing.new
t.changed? # => false
t.employer_wcb_changed? # => false
# Now set the attribute and note the dirty bits.
t.employer_wcb = 0.525
t.changed? # => true
t.employer_wcb_changed? # => true
t.id_changed? # => false
# The dirty bit goes away when you save changes.
t.save
t.changed? # => false
t.employer_wcb_changed? # => false
于 2009-12-15T01:37:59.520 回答
2
如果您不想使用 rail 的内置脏位功能(例如您想出于其他原因覆盖),则不能使用别名方法(请参阅我对上面史蒂夫条目的评论)。但是,您可以使用对 super 的调用来使其工作。
def employer_wcb=(val)
# Set the dirty bit to true
dirty = true
super val
end
这工作得很好。
于 2009-12-15T19:29:31.147 回答