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?
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:
Ignore the warning and wait for the gem to be patched.
Fork the gem, merge the pull request, and use your forked version until the gem merges the pull request in question.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With