Reputation: 238727
I have a method ("before filter") in my Rails controller that needs to respond with a 422 status code if some params are missing. How can I do this from within a before filter?
class FoobarsController < ApplicationController
before_action :find_parent
def create
if @parent.foobar.save
render @parent.foobar, status: :created
else
render @parent.foobar.errors, status: :unprocessable_entity
end
end
def find_parent
if params[:parent_id]
@parent = Parent.find(params[:parent_id])
elsif params[:foobar_id]
@parent = Foobar.find(params[:foobar_id])
else
raise 'Missing parent ID param' # TODO: respond with 422 status instead of 500
end
end
end
Upvotes: 1
Views: 1409
Reputation: 7655
:status
option of render
method will do the trick:
render status: 422
or
render status: :unprocessable_entity
More info can be found here.
Also as @MaxWilliams noted in the comment, in complicated code, like yours, it's a good practice to use return
with render
statement:
render(status:422) and return
Upvotes: 2