Ruby on rails Rails6SQL方法的语法

Ruby on rails Rails6SQL方法的语法,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,以下警告出现在某些控制器操作上 DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): "CASE id WHEN 343[...]". Non-attribute arguments will be disallowed in Rails 6.0. This method

以下警告出现在某些控制器操作上

DEPRECATION WARNING: Dangerous query method (method whose arguments are used as raw SQL) called with non-attribute argument(s): 
"CASE id WHEN 343[...]". 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. 
但“用户提供”值不会调用此方法:

def find_已订购(ids)
order_子句=“案例id”
id.each_与_索引do | id,索引|

order_子句严格来说,它不是“用户提供的值”,但Rails无法知道字符串是来自用户还是在程序中硬编码

解决这个问题的方法是使用

包装一个已知的安全SQL字符串以传递给查询方法,例如

def find_ordered(ids)
  order_clause = "CASE id "
  ids.each_with_index do |id, index|
    order_clause << "WHEN #{id} THEN #{index} "
  end
  order_clause << "ELSE #{ids.length} END"
  where(id: ids).order(order_clause)
end
where(id: ids).order(Arel.sql(order_clause))