pcasa
pcasa

Reputation: 3730

Dirty and check if email attribute changed?

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?

Upvotes: 5

Views: 2058

Answers (2)

Dorian
Dorian

Reputation: 23939

I recommend using Rails Dirty methods:

if @user.email.changed?
  # ...
end

But you can also do:

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

Upvotes: 0

John Topley
John Topley

Reputation: 115332

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]'] }

Upvotes: 11

Related Questions