Rails无法将嵌套的哈希传递给控制器​​参数

时间:2018-11-07 11:17:17

标签: ruby-on-rails rspec parameters controller

由于我正在使用Rspec测试我的控制器是否工作正常,因此我做了以下事情:

在test_rspec.rb中,

before do
  params = {
    date_begin: "2018-10-01", 
    date_end: "2018-10-05", 
    options: {country_code: "US"}
  }

  get :index, params: params, as: :json
end

it do
  expected(response).to have_http_response(200) }
end

在test_controller.rb中,

def index
  puts params_checker
  render json: Test.report(params_checker[:date_begin], 
                           params_checker[:date_end],
                           params_checker[:options])
end

private
  def params_checker
    params.permit(:date_begin, :date_end, :options)
  end

当我使用rspec命令运行代码时,出现了问题,带有嵌套哈希:options的参数消失了!下面是终端中params的输出及其一些错误信息:

> {"date_begin"=>"2018-10-01", "date_end"=>"2018-10-03"}
> ArgumentError:
   wrong number of arguments (given 3, expected 2)

我在Internet上到处搜索并尝试了一些解决方案,但无济于事。我知道此错误是由参数丢失引起的。有谁能帮助我弄清楚为什么在我的情况下哈希不能传递给控制器​​的参数吗?

note:我正在使用rails 5.1.6

1 个答案:

答案 0 :(得分:0)

在寻找了很多解决方案之后,我找到了一种清晰的方法来处理它。 Strong parameters handling对我有很大帮助。

首先,如果要传递数组或哈希,无论参数是什么,仅当它是嵌套参数时,都应在params.permit()语句中声明它,并添加允许传递的键[]因为permit仅允许标量值通过,并且如果未声明特定参数,则默认情况下会过滤散列和数组。代码如下:

private
  def stat_params
    params.permit(:date_begin, :date_end, options: [:country_code])
  end

第二秒,当使用Rspec测试控制器时,嵌套参数将作为<ActionController::Parameters:xxxx>类型传递,因此您必须向此特定参数添加to_unsafe_h语句,如下所示:< / p>

def index
  render json: Test.report(stat_params[:date_begin],
                           stat_params[:date_end],
                           stat_params[:options].to_unfsafe_h)
end

最后对我来说很好。

相关问题