我正在尝试更新到 Rails 5,我收到以下弃用警告:
DEPRECATION WARNING: Method to_hash is deprecated and will be removed in Rails 5.1, as
ActionController::Parametersno 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. Instead, consider using one of these documented methods which are not deprecated: http://api.rubyonrails.org/v5.0.0/classes/ActionController/Parameters.html (called from column_header at /Data/Projects/portal/trunk/app/helpers/application_helper.rb:114)
警告所在的行如下所示:
link_to(name,
{
action: action_name,
params: params.merge({ order: key, page: nil })
},
{
title: "Sort by this field",
}) +
如您所见,我没有调用to_hash。也许 Rails 是。也许其他一些 gem 是。我无从得知,因为他们认为提供堆栈跟踪不值得。 (专业提示 - 通常 值得提供堆栈跟踪!)
所以无论如何,我点击了链接,打算找一个替代品,然后 the merge method does not appear to be deprecated ,但也许他们只是忘记记录弃用状态,所以我不能确定。
那么我应该怎么做才能清除它?
最佳答案
.to_h根据a comment on the Rails PR,您可以调用.to_h 来获得安全哈希.
现在有三种将参数转换为散列的方法。
.to_h 表示“如果我没有调用 .permit,则假定不允许任何事情。”.to_unsafe_h 的意思是“如果我没有调用 .permit,则假设一切都是允许的。”.to_hash 现在不明确。 Rails 将其视为 .to_unsafe_h,但会打印一条警告,因为您没有明确说明您想要上面两个选项中的哪一个。 首先,让我们看看如果您没有调用 .permit 会发生什么。在 Rails 5.0 控制台中:
> params = ActionController::Parameters.new({yes: "y", no: "n"})
> params.to_h
{} # empty hash because nothing has been permitted
> params.to_unsafe_h
{"yes"=>"y", "no"=>"n"} # raw values with no warning; you asked for it
> params.to_hash
# (puts deprecation warning - if you want unsafe values, say so)
{"yes"=>"y", "no"=>"n"} # returns raw values
但是,如果您先调用 .permit,将无法获取非允许值。
> params = ActionController::Parameters.new({yes: "y", no: "n"})
> params = params.permit(:yes)
# (puts warning about unpermitted parameter :no)
> params.to_h
{"yes"=>"y"} # permitted values only
> params.to_unsafe_h
{"yes"=>"y"} # permitted values only
> params.to_hash
# (puts deprecation warning, but still safe)
{"yes"=>"y"} # permitted values only
所以:
.permit 将您期望的值列入白名单.to_h 确保如果您忘记了第 1 步,则任何事情都无法通过.permit 并调用 .to_unsafe_hash.to_hash 因为它现在不明确关于ruby-on-rails - 如何解决弃用警告 "Method to_hash is deprecated and will be removed in Rails 5.1",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38710904/