12

我将我的 rails 5.1.4 应用程序更新为 5.2.0。我的一个模型中有以下范围:

  scope :by_category, lambda { |category_slug|
    category_ids = Category.find_by(slug: category_slug)&.subtree_ids
    where(category_id: category_ids)
  }

由于该范围,Rails 向我返回以下错误:

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): "coalesce(\"categories\".\"ancestry\", '')". Non-attribute arguments will be disallowed in Rails 6.0. This method should not be called with user-provided values, such as request parameters or model attributes. Known-safe values can be passed by wrapping them in Arel.sql()

我该如何解决?

4

1 回答 1

18

问题是ordered_by_ancestry范围

scope :ordered_by_ancestry, Proc.new { |order|
  if %w(mysql mysql2 sqlite sqlite3 postgresql).include?(connection.adapter_name.downcase) && ActiveRecord::VERSION::MAJOR >= 5
    reorder("coalesce(#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(ancestry_column)}, '')", order)
  else
    reorder("(CASE WHEN #{connection.quote_table_name(table_name)}.#{connection.quote_column_name(ancestry_column)} IS NULL THEN 0 ELSE 1 END), #{connection.quote_table_name(table_name)}.#{connection.quote_column_name(ancestry_column)}", order)
  end
}

正在将原始的 SQL 字符串传递给,#reorder并且正如警告所述,这在 Rails 5.2 中已被弃用(并将在 Rails 6 中完全删除)。

刚刚提交了一个拉取请求Arel.sql,该请求通过将这些字符串包装在调用中来解决此问题。我希望这会很快合并(尽管拉取请求Arel.sql在第二个分支中缺少一个调用),但与此同时,您有一些选择:

  1. 忽略警告并等待 gem 被修补。

  2. 分叉 gem,合并拉取请求,并使用您的分叉版本,直到 gem 合并有问题的拉取请求。

  3. 手动更换ordered_by_ancestry范围:

    def self.ordered_by_ancestry(order)
      reorder(Arel.sql("coalesce(#{connection.quote_table_name(table_name)}.#{connection.quote_column_name(ancestry_column)}, '')"), order)
    end
    

    并等待合并请求。


更新:修复此警告的拉取请求刚刚合并,因此无需再等待,您应该能够从 GitHub 获取最新信息并继续做更多有趣的事情。感谢kbrock整理出来。

于 2018-04-17T21:56:39.267 回答