Reputation: 2390
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_action
s from executing?
Things I know of:
after_action
render :something and return
doesn't stop after_action
screate!
) 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
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
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