【问题标题】:DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s)弃用警告:使用非属性参数调用的危险查询方法(其参数用作原始 SQL 的方法)
【发布时间】:2018-04-17 21:14:36
【问题描述】:

我将我的 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()

我该如何解决这个问题?

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-5.2


【解决方案1】:

问题是ordered_by_ancestry scope:

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 中完全删除)。

刚刚提交了一个pull request,它通过将这些字符串包装在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
    

    并等待合并请求。


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2016-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多