Dan Benjamin
Dan Benjamin

Reputation: 900

Rails - Auto fill database field based upon change in another field

I have a field in my database that contains the user's email. In addition, I have a field that contains the sha1 of the email of the user.

I was wondering if there's a way for me to auto-populate the sha1 field based on any change made in original email field.

Thanks in advance, Dan

Upvotes: 0

Views: 532

Answers (1)

Agis
Agis

Reputation: 33626

You can do this using a before_save callback:

class User
  before_save :update_email_sha1, if: :email_changed?

  private

  def update_email_sha1
    self.email_sha1 = generate_email_sha1(email)
  end
end

Upvotes: 2

Related Questions