Seeing what has changed in ActiveRecord

I have a callback (before_save) that I want to trigger only when
certain fields within a record have changed. For example given a user
record with ‘username’, ‘password’ and ‘date_of_birth’ I would like
the callback to do something only when the ‘username’ or ‘password’
changes or when the ‘date_of_birth’ changes from nil to something
real. For example, how would I write…

before_save :audit_changes

def audit_changes
if old.username != new.username
audit("The username has changed from #{old.username} to
#{new.username})
end

if old.password != new.password
audit(“The user has changed their password”)
end

if old.date_of_birth == nil and new.date_of_birth != nil
audit(“The user has finally set their date of birth”)
end
end

Now this is just a little example of what I want to do, don’t get hung
up on the example, but how can I write this?

On Mon, Jan 24, 2011 at 11:49 AM, Peter H.
[email protected] wrote:

if old.username != new.username
end

Now this is just a little example of what I want to do, don’t get hung
up on the example, but how can I write this?

Active Record has API for that:

http://api.rubyonrails.org/classes/ActiveModel/Dirty.html

so you basically could test whether username_changed?, for example.

The examples in AM::Dirty include the module by hand, but you don’t
need to do that in AR models.

Thank you, I’ve been googling away like crazy but forgot to use that
magic word DIRTY. Damn I knew it was available.

Thank you.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs