Cannon Moyer
Cannon Moyer

Reputation: 3174

skip after_update if given field is the only updated attribute - Ruby on Rails

I've got a model that can be updated twice within the same update request.

Here is my filter:

after_update :make_api_call

In my function, I update the api and then save the response on the same object.

def make_api_call
    response = SomeAPI.call    
    self.api_response = response
    self.save
end

This will obviously cause the update function to be called in an endless loop. I want the make_api_call function to be skipped if the only attribute being updated is the api_response attribute. Executing the API call before update is not an option do to some nested resources associated with the record.

Upvotes: 1

Views: 656

Answers (2)

John Baker
John Baker

Reputation: 2398

As of Rails 5.1 you could also do:

after_update :make_api_call, unless: :saved_change_to_response?

The saved_change_to_response? method comes from ActiveRecord::AttributeMethods::Dirty, which allows us to check if a specific attribute has changed by prepending saved_change_to_ to the attribute name.

Upvotes: 1

abax
abax

Reputation: 787

You could use ActiveRecord::Persistence#update_columns which skips callbacks.

def make_api_call
  response = SomeAPI.call    
  update_columns(api_response: response)
end

Upvotes: 1

Related Questions