views:

38

answers:

2

Last part of my project, Hopefully.

Need to check if user.email attribute changes. If it does, then need to tell mailchimp to change or add the email.

Looks like Dirty will do this, but have never used it before. How can I catch the change in a block, or pass it to a block, and then update the attribute?

A: 

You can do :

if @user.email != params[:user][:email]
  // …
end

(I could be not exactly this code)

Dorian
+1  A: 

Using the ActiveRecord::Dirty module is pretty straightforward:

bob = User.find_by_email('[email protected]')
bob.changed?       # => false

bob.email = '[email protected]')
bob.changed?       # => true
bob.email_changed? # => true
bob.email_was      # => '[email protected]'
bob.email_change   # => ['[email protected]', '[email protected]']
bob.changed        # => ['email']
bob.changes        # => { 'email' => ['[email protected]', '[email protected]'] }
John Topley
Saw the API, but can't get it to work. I assume you have to include the Dirty class, but can't find how to do it. At the moment "if @user.email_changed?"
pcasa
The Dirty module is included by default. Are you getting an error message?
John Topley
Not getting an error but its not detecting the change. If I try Dorian's recommendation it does see the change.
pcasa
Are you saving the record before trying to see the change? Saving resets the dirty state.
John Topley
"if @user.email_changed?" is in update but before "if @user.update_attributes(params[:user])". Should it be else where? before_filter?
pcasa
Nice answer, I did not know it, very nice.
Dorian