ActionController::Parameters 弃用警告:方法大小已弃用,将在 Rails 5.1 中删除
ActionController::Parameters deprecation warning: Method size is deprecated and will be removed in Rails 5.1
我最近遇到了这个弃用警告
DEPRECATION WARNING: Method size is deprecated and will be removed in Rails 5.1, as ActionController::Parameters
no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited.
参数看起来像这样:
<ActionController::Parameters { "objects" =>
<ActionController::Parameters {
"0"=>{"priority"=>"24", "style"=>"three_pictures"},
"1"=>{"priority"=>"24", "style"=>"three_pictures"},
"2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false> } permitted: false>
我试图找到 objects
的大小,如下所示:
params[:objects].size
然后我用 length
和 count
尝试了同样的事情,这导致了同样的警告。解决这个问题的方法是什么? .keys.length
是可行的方法,但这是正确的方法还是我在这里遗漏了什么?
对于哈希,可以通过.size
方法求出大小。
问题不在于此处的大小方法,问题在于 ActionController::Parameters
不是散列,
看里面第一行ActionController::Parameters
"0"=>{priority"=>"24", "style"=>"three_pictures"}
priority
之前缺少 "
应该跟在后面
"0"=>{"priority"=>"24", "style"=>"three_pictures"}
在此之后 .size method
应该可以工作了
如评论中所述,您必须将 params
转换为 Hash,因为在 Rails 5 params
中不再继承自 Hash
。所以 .size
、.length
和 .count
不会直接作用于参数。
如何将其转换为 Hash
(可以使用更短的代码):
permitted_params = params.require(:your_model_name).permit(
:product_inspirationals => [
:priority,
:style
]
).to_h
puts permitted_params[:product_inspirationals].length
不了解您的模型结构,因此您必须根据需要进行调整。
我最近遇到了这个弃用警告
DEPRECATION WARNING: Method size is deprecated and will be removed in Rails 5.1, as
ActionController::Parameters
no longer inherits from hash. Using this deprecated behavior exposes potential security problems. If you continue to use this method you may be creating a security vulnerability in your app that can be exploited.
参数看起来像这样:
<ActionController::Parameters { "objects" =>
<ActionController::Parameters {
"0"=>{"priority"=>"24", "style"=>"three_pictures"},
"1"=>{"priority"=>"24", "style"=>"three_pictures"},
"2"=>{"priority"=>"24", "style"=>"three_pictures"}
} permitted: false> } permitted: false>
我试图找到 objects
的大小,如下所示:
params[:objects].size
然后我用 length
和 count
尝试了同样的事情,这导致了同样的警告。解决这个问题的方法是什么? .keys.length
是可行的方法,但这是正确的方法还是我在这里遗漏了什么?
对于哈希,可以通过.size
方法求出大小。
问题不在于此处的大小方法,问题在于 ActionController::Parameters
不是散列,
看里面第一行ActionController::Parameters
"0"=>{priority"=>"24", "style"=>"three_pictures"}
priority
"
应该跟在后面
"0"=>{"priority"=>"24", "style"=>"three_pictures"}
在此之后 .size method
应该可以工作了
如评论中所述,您必须将 params
转换为 Hash,因为在 Rails 5 params
中不再继承自 Hash
。所以 .size
、.length
和 .count
不会直接作用于参数。
如何将其转换为 Hash
(可以使用更短的代码):
permitted_params = params.require(:your_model_name).permit(
:product_inspirationals => [
:priority,
:style
]
).to_h
puts permitted_params[:product_inspirationals].length
不了解您的模型结构,因此您必须根据需要进行调整。