mr_muscle
mr_muscle

Reputation: 2900

Rails 6 call action if specific field changed

In my Rails 6 app I've got User model which has first_name and last_name fields. Both of these fields are required to create a new record. Now I want to trigger the IdentityCheck.new(self).call service each time when user updates his first_name or last_name.

Naturally I've tried something like below:

class User < ApplicationRecord
  after_update :restart_identity_check, if: :first_name_changed? || :last_name_changed?

  private

  def restart_identity_check
    IdentityCheck.new(self).call
  end
end

But I don't know why it won't worked. Is there a way to do this?

Upvotes: 0

Views: 1007

Answers (1)

Jo&#227;o Fernandes
Jo&#227;o Fernandes

Reputation: 721

That's not the correct syntax for if.

after_update :restart_identity_check, if: Proc.new { |user| user.first_name_changed? || user.last_name_changed? }

You may wish to create an alternate method, like this:

after_update :restart_identity_check, if: :must_restart_identity_check?

# I'd make this private
private 

def must_restart_identity_check?
  first_name_changed? || last_name_changed?
end

Remember that after_update runs before record is commited to the database. So, if something happens in between, you are going to restart_identity_check even if your User changes is not commited to the database. I'd use after_update_commit just in case.

Upvotes: 3

Related Questions