开发者

ruby on rails add functionality to model property change

In my rails model, I have a decimal property called employer_wcb. I wou开发者_JAVA百科ld like it if, when employer_wcb was changed, a dirty bit was set to true. I'd like to override the employer_wcb setter method. Any way to do so (in particular using metaprogramming)?


So actually, as of Rails v2.1, this has been baked into Rails. Have a look at the documentation for ActiveRecord::Dirty. In summary:

# 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


If you don't want to use rail's built in dirty bit functionality (say you want to override for other reasons) you cannot use alias method (see my comments on Steve's entry above). You can however use calls to super to make it work.

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

This works just fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜