我的Rails控制器中有一个方法("在过滤器"之前),如果缺少一些参数,需要用422状态代码进行响应。如何在之前的过滤器中执行此操作?
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
答案 0 :(得分:1)
:status
render
方法的选项可以解决问题:
render status: 422
或
render status: :unprocessable_entity
可以找到更多信息here。
同样@MaxWilliams在评论中指出,在复杂的代码中,与您的一样,将return
与render
声明一起使用是一种很好的做法:
render(status:422) and return