![](/img/trans.png)
[英]DEPRECATION WARNING: Method length is deprecated and will be removed in Rails 5.1
[英]ActionController::Parameters deprecation warning: Method size is deprecated and will be removed in Rails 5.1
我最近遇到了這個棄用警告
棄用警告:方法大小已棄用,將在Rails 5.1中刪除,因為
ActionController::Parameters
不再繼承哈希。 使用此棄用行為會暴露潛在的安全問題。 如果您繼續使用此方法,則可能會在您的應用中創建可被利用的安全漏洞。
Params看起來像這樣:
<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
是有效的,但這是正確的方法,還是我錯過了什么?
正如評論中所提到的,你必須將params
轉換為Hash,因為在Rails 5中, params
不再繼承Hash
。 所以.size
, .length
和.count
不能直接用於params。
如何將其轉換為Hash
(可能更短的代碼):
permitted_params = params.require(:your_model_name).permit(
:product_inspirationals => [
:priority,
:style
]
).to_h
puts permitted_params[:product_inspirationals].length
不了解您的模型結構,因此您必須根據需要進行調整。
對於散列,您可以通過.size
方法找到大小。
問題不在於這里的size方法,問題在於ActionController::Parameters
,它不是hash,
查看ActionController::Parameters
中的第一行
"0"=>{priority"=>"24", "style"=>"three_pictures"}
它應該跟隨"
priority
之前失蹤"
"0"=>{"priority"=>"24", "style"=>"three_pictures"}
在此之后.size method
應該正常工作
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.