在我的轨道模型中,我有一个名为employer_wcb小数属性。我想,如果,当employer_wcb被改变,脏位被设置为true。我想重写employer_wcb setter方法。任何方式这样做(特别是在使用元编程)?

有帮助吗?

解决方案

因此,实际上,作为导轨的V2.1,这已被烘焙到导轨。看一看在文档的ActiveRecord ::脏。总结:

# 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

其他提示

如果你不希望使用内置的脏位功能轨的(说你要覆盖其它原因)不能使用别名方法(见上文我对史蒂夫的条目评论)。但是,您可以使用超级调用,使其工作。

  def employer_wcb=(val)
    # Set the dirty bit to true
    dirty = true
    super val
  end

此工作得很好。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top