Search code examples
ruby-on-rails-3jrubyjrubyonrailsactioncontroller

after_commit for rails controller


I know that an after_commit callback is provided for ActiveRecord objects in Rails 3. However, I would like to get access to this functionality in a Rails Controller.

The intent is to do something like this in the controller:

rescue_from AccountError, :with => :render_internal_error

after_commit :render_created, :on => :create

def create
  Account.transaction do
    modify_underlying_system
    @account.save!
  end
end

protected
def render_created
  render :status => 201, :json => {...}
end

def render_internal_error
  render :status => 500, :json => {...}
end

Is there some way I could achive this? I do not want to use the ActiveRecord after_commit callback, because it would mean breaking the separation between model and controller by having the model do rendering, which is something it should not be doing.


Solution

  • This should do what you're trying to do:

    def create
      begin
        Account.transaction do
          modify_underlying_system
          @acount.save!
        end
        render :status => 201, :json => {...}
      rescue ActiveRecord::RecordInvalid
        render :status => 500, :json => {...}
      end
    end
    

    I didn't test it, but that looks about right.