views:

176

answers:

2

In my rails model, I have a decimal property called employer_wcb. I would 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)?

+7  A: 

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
Andres Jaan Tack
Absolutely. Two caveats though: We don't know which version of Rails is being targeted (unlikely to be an issue but hey!) and I do not believe that ActiveRecord::Dirty tracks virtual attributes. Asker did not specify nature of employer_wcb.
Steve Graham
+1 - @Daniel: This is the best answer to accept if you're using > 2.1 and employer_wcb is not a virtual attribute.
Steve Graham
ActiveRecord::Dirty was a plugin before accepted into 2.1. http://code.bitsweat.net/svn/dirty/
EmFi
+2  A: 

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.

Daniel
Nice! That's so much more elegant than alias!
Andres Jaan Tack