Rails 5 测试控制器未过滤的参数 [英] Rails 5 testing controller unfiltered params
问题描述
我最近将我的应用程序升级到 Rails 5,当我测试我的控制器时,我收到以下错误:ActionController::UnfilteredParameters:无法将不允许的参数转换为哈希
.
I have recently upgraded my application to Rails 5 and when I am testing my controller I am getting the following error:
ActionController::UnfilteredParameters: unable to convert unpermitted parameters to hash
.
我的控制器代码如下所示:
My controller code looks like this:
def bid
widget_mode = params.include?(:widget)
if !@auction.published?
redirect_to '/' #go to the homepage
elsif @auction.third_party?
redirect_to @auction.third_party_bidding_url
elsif current_user && current_user.clerk? &&
!@auction.listing? &&
(@auction.items_count == 1 || params["section"] == "auction") &&
!widget_mode
redirect_to action: 'clerk', id: @auction.id, params: params.slice(:item, :section)
else
# Make sure the auction is in firebase
exists = @auction.rt_get('updated_at').body.to_i > 0 rescue false
@auction.queue_realtime_update unless exists
end
end
我的测试代码如下所示:
and my test code looks like this:
test "should redirect to powerclerk if multi item auction and params section = auction" do
sign_in users(:clerk)
a = auctions(:kenwood_dr)
assert a.items.count > 1, "Expected auction to have more than one item"
get :bid, params: {id: a.id, item: a.items.first.id, section: "auction"}
assert_redirected_to "/clerk/1?item=1§ion=auction"
end
我尝试添加:params.permit(:item, :section, :id, :controller, :action, :widget)
到我的 bid
控制器方法的开头,这没有什么区别.任何见解将不胜感激.
I tried adding:
params.permit(:item, :section, :id, :controller, :action, :widget)
to the beginning of my bid
controller method and that didn't make a difference. Any insight would be appreciated.
推荐答案
在 ActionController::Parameters 的实例上调用
没有任何允许的键(文档).to_h
或 to_hash
时发生此错误
This error occurs when calling to_h
or to_hash
on an instance of ActionController::Parameters
that doesn't have any permitted keys (documentation).
由于 ActionController::Parameters#slice
返回一个相同的实例,这段代码不会给你一个看起来像的散列:params.slice(:item, :section)
.
Since ActionController::Parameters#slice
returns an instance of the same, this code does not give you a hash like it would seem: params.slice(:item, :section)
.
在大多数情况下,您可以在参数实例上使用 permit
而不是 slice
.如果您想绕过 ActionController::Parameters
的安全访问白名单,您可以使用 permit!
并使用 ActionController::Parameters#slice
,或者,如果您想在没有清理的情况下转换为哈希,您可以使用 to_unsafe_h.
In most cases you can use permit
instead of slice
on parameters instances. If you ever want to bypass the safe access whitelisting of ActionController::Parameters
you can use permit!
and use ActionController::Parameters#slice
, or if you want to convert to a hash without sanitization you can use to_unsafe_h.
这篇关于Rails 5 测试控制器未过滤的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!