DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s)

两盒软妹~` 提交于 2019-12-23 08:29:42

问题


I updated my rails 5.1.4 app to 5.2.0. I have the following scope in one of my models:

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

Rails returns me following error because of that scope:

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()

How can I fix that?


回答1:


The problem is that the 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
}

is passing a raw string of SQL to #reorder and, as the warning states, this is deprecated in Rails 5.2 (and will be removed altogether in Rails 6).

A pull request was just submitted which fixes this by wrapping those strings in Arel.sql calls. I'd expect this to merged quickly (despite the pull request missing an Arel.sql call in the second branch) but in the mean time, you have some options:

  1. Ignore the warning and wait for the gem to be patched.

  2. Fork the gem, merge the pull request, and use your forked version until the gem merges the pull request in question.

  3. Manually replace the ordered_by_ancestry scope:

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

    and wait for the pull request to get merged.


UPDATE: The pull request which fixes this warning was just merged so there's no need to wait anymore, you should be able to grab the latest from GitHub and get on with more interesting things. Thanks to kbrock for sorting this out.



来源:https://stackoverflow.com/questions/49887593/deprecation-warning-dangerous-query-method-method-whose-arguments-are-used-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!