On Mon, Jan 24, 2011 at 11:49 AM, Peter Hickman
<[email protected]> wrote:

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

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.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to