How can I retry an ActionController action inside a rescue_from for a StaleObjectError

65 Views Asked by At

I want to do something like this:

MyController < ApplicationController
  rescue_from ActiveRecord::StaleObjectError, :retry

I have an app where users and admins are occasionally updating the same object at the same time and they sometimes collide. The actions are fairly short lived and should succeed on a retry, so it would be great to try without involving the client.

It would be OK if this happened at another layer in the stack too. Somewhere in Rack perhaps?

I looked for retry methods in the Rails API and didn't find anything. My internet searches and Rails discussion searches were also fruitless. I could, of course, put code in the controller like the following, but I'd like to do it for all the actions I have without duplicating that everywhere.

def myaction
  # do stuff
rescue ActiveRecord::StaleObjectError
  retry
end
1

There are 1 best solutions below

0
Amol Mohite On

You can try below

class MyController < ApplicationController
  rescue_from ActiveRecord::StaleObjectError, with: : retry_after_stale_object_error

  def myaction
    retry_on_stale_object_error do
      # do stuff
    end
  end

  private

  def handle_stale_object_error
    # Any addition stuff on failure if you want
    retry
  end

  def retry_on_stale_object_error
    tries = 1

    begin
      yield
    rescue ActiveRecord::StaleObjectError
      tries += 1
      retry if tries < 3
      # can add if retry attempts are over
      raise
    end
  end
end

I hope this will help you. Reference