Topic: ActiveRecord -> update attribute trigger

Hi all,

I have a question about the update of a single attribute that should trigger a private method called change_state. The model class looks like this:

class Proposal < ActiveRecord::Base
  belongs_to :state
  has_many :states

  validates_presence_of :state_id
  before_validation_on_create :init_state

  private
    def init_state
      change_state(Negotiation.new)
    end

    def change_state(state)
      Proposal.transaction(self) do
        self.state = state
        self.states << state
      end
    end
end


Basically if I would do
p.policy_number = 123445

on an instance "p" of Proposal, then I want it to trigger a call to the private method like
change_state(Policy.new)

if the value for policy_number was NULL in the database. Both Negotation and Policy are sub classes of the State class.

Thanks for your reply,

Mark

Re: ActiveRecord -> update attribute trigger

You can override the setter method for this attribute. For example:

# in proposal.rb
def policy_number=(new_policy_number)
  self[:policy_number] = new_policy_number
  change_state(Policy.new) if new_policy_number.nil?
end

I think there's also a plugin out there where you can set a before_update_attribute or something, similar to before_save. Not sure what it's called though.

Railscasts - Free Ruby on Rails Screencasts