(ActiveRecord) Callback notes: after_commit

Posted Almost 7 years ago. Visible to the public.
class MyModel 

  after_commit :api_call_and_update, on: :create

  ...
  
  def api_call_and_update
    # Some call to an API service
    self.update(attribute_one: 'New Value')
  end

The above will result in a Stack level too deep error.

The create lifecycle ends only when the last callback has finished. This means any update on the model will lead to an infinite loop, as the on: :create callbacks will be fired again since the initial create cycle hasn't finished (thus it's not considered an update but still create.

One way to avoid this is to use update_columns instead, which bypasses callbacks and validations.

This Github Issue Show archive.org snapshot has more information.

Greg
Last edit
Almost 7 years ago
Greg
Posted by Greg to Ruby on Rails (2017-06-26 23:50)