如何从前一个过滤器中暂停Rails控制器操作并使用422不可处理的实体进行响应?

时间:2015-09-28 15:46:35

标签: ruby-on-rails

我的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

1 个答案:

答案 0 :(得分:1)

:status render方法的选项可以解决问题:

render status: 422

render status: :unprocessable_entity

可以找到更多信息here

同样@MaxWilliams在评论中指出,在复杂的代码中,与您的一样,将returnrender声明一起使用是一种很好的做法:

render(status:422) and return