如何解决弃用警告 "Method to_hash is deprecated and will be removed in Rails 5.1"

How do I resolve the deprecation warning "Method to_hash is deprecated and will be removed in Rails 5.1"

我正在尝试更新到 Rails 5,我收到以下弃用警告:

DEPRECATION WARNING: Method to_hash 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. 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 是。我无从得知,因为他们认为提供堆栈跟踪不值得。 (专业提示 - 通常 值得提供堆栈跟踪!)

所以无论如何,我遵循了 link,计划寻找替代品,并且 the merge method does not appear to be deprecated,但也许他们只是忘记记录弃用状态,所以我不能确定。

那么我应该怎么做才能清除它?

使用.to_h

根据a comment on the Rails PR.

,您可以调用.to_h来获得安全哈希

现在有三种将参数转换为散列的方法。

  • .to_h表示"if I haven't called .permit, assume nothing is allowed."
  • .to_unsafe_h 表示 "if I haven't called .permit, assume everything is allowed."
  • .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

所以:

  1. 始终使用 .permit 将您期望的值列入白名单
  2. 使用 .to_h 确保如果您忘记了第 1 步,则任何事情都无法通过
  3. 如果您真的想要原始值,请不要调用 .permit 并调用 .to_unsafe_hash
  4. 不要调用 .to_hash 因为它现在不明确