试图让 POST 返回 400 个错误的请求 [英] Trying to get a POST to return 400 bad request

查看:49
本文介绍了试图让 POST 返回 400 个错误的请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个通过关联构建新模型的 create 方法,如果 POST 请求中没有参数,我希望它返回带有一些文本的 400 响应.但是,我收到一个错误.

I have a create method that builds a new model through an association and I was expecting it to return a 400 response with some text if no params were in the POST request. However, I get an error.

这是在 Rails 4.0.2 中

This is in Rails 4.0.2

控制器方法:

  def create
    @cast_profile = current_user.build_cast_profile(cast_profile_params)
    if @cast_profile.save
      redirect_to cast_profile_path
    else
      render :edit
    end
  end

  def cast_profile_params
    params.require(:cast_profile).permit(:name, :email, :public)
  end

如果我传递参数一切正常,但我正在尝试测试错误的请求场景.这是错误:

If I pass the params its all fine but I'm trying to test the bad request scenario. Here's the error:

ActionController::ParameterMissing: param not found: cast_profile

我可以明确地拯救它,但我认为强参数应该自动做到这一点.

I could rescue it explicitly but I thought strong parameters was supposed to do that automatically.

推荐答案

行为如下:

处理未经许可的密钥

默认情况下,未明确允许的参数键将是登录开发和测试环境.在其他环境中这些参数将被简单地过滤掉并忽略.

By default parameter keys that are not explicitly permitted will be logged in the development and test environment. In other environments these parameters will simply be filtered out and ignored.

此外,可以通过更改config.action_controller.action_on_unpermitted_pa​​rameters 中的属性你的环境文件.如果设置为 :log,则不允许的属性将被记录,如果设置为 :raise 将引发异常.

Additionally, this behaviour can be changed by changing the config.action_controller.action_on_unpermitted_parameters property in your environment files. If set to :log the unpermitted attributes will be logged, if set to :raise an exception will be raised.

(来源)

我建议以 400 状态(错误请求)从这个异常中解救:

I would suggest rescuing from this exception with 400 status (Bad Request):

rescue_from ActionController::ParameterMissing do
  render :nothing => true, :status => :bad_request
end

这篇关于试图让 POST 返回 400 个错误的请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆