ruby-on-railsrubymetaprogrammingalias-method

ruby on rails add functionality to model property change


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)?


Solution

  • 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