Tutorial :Dirty and check if email attribute changed?



Question:

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?


Solution:1

I recommend using Rails Dirty methods:

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

But you can also do:

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


Solution:2

Using the ActiveRecord::Dirty module is pretty straightforward:

bob = User.find_by_email('bob@example.org')  bob.changed?       # => false    bob.email = 'robert@example.org')  bob.changed?       # => true  bob.email_changed? # => true  bob.email_was      # => 'bob@example.org'  bob.email_change   # => ['bob@example.org', 'robert@example.org']  bob.changed        # => ['email']  bob.changes        # => { 'email' => ['bob@example.org', 'robert@example.org'] }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »