Piotr Kruczek
Piotr Kruczek

Reputation: 2390

Rails controller skip after_action

Let's say I have a controller as follows:

class ExampleController < ApplicationController

  after_action -> { puts 'Call me only on success' }

  def create
    obj = Obj.create(obj_params)
    if obj.errors.empty?
      render json: obj
    else
      render json: { errors: obj.errors }, status: 422
    end
  end
end

Is there a clean way to stop all after_actions from executing? Things I know of:

  1. Set some kind of instance variable and check it in every after_action
  2. render :something and return doesn't stop after_actions
  3. raising an error (like create!) would work, but I use it when I don't want to return error specifics and still respond with 422

I'd settle for something like render :foo and do_not_call_afters

Upvotes: 2

Views: 2986

Answers (2)

Aaron Breckenridge
Aaron Breckenridge

Reputation: 1819

You can ask the response if it was successful:

after_action :call_me_on_success, if: -> { response.successful? }

This passes for all 2XX codes:

response.method(:successful?).source
=> "def successful; status >= 200 && status < 300; end"

Upvotes: 7

Vivek Singh
Vivek Singh

Reputation: 635

One way to go with check the instance variable:

after_action -> { puts 'Call me only on success' } , if: -> { @foo }

set it in create method based on your condition.

Upvotes: -1

Related Questions