Is it possible to use question marks in 'order' methods-clauses?

 ̄綄美尐妖づ 提交于 2019-12-24 06:01:30

问题


I am using Ruby on Rails 3.2 and I would like to know if there is a way to make the following:

@categories.order('user_id = ? DESC', params[:id])
@categories.order('user_id = ? DESC', @user.id)

# Note: It is almost the same as `@categories.where('user_id = ?', params[:id])`
# but for the `order` clause.

Above statements generates this error:

ActiveRecord::StatementInvalid (Mysql2::Error: You have an error in your SQL 
syntax; check the manual that corresponds to your MySQL server version for the 
right syntax to use near '? DESC, ...

回答1:


If you are trying to change the order based on the user_id, returning those that match first, you should be using a CASE statement.

In raw SQL, it would look like this:

SELECT * FROM Categories ORDER BY CASE user_id WHEN 34 THEN 1 ELSE 2 END

That would bring all of rows where user_id is 34 to the top, leaving the rest to default ordering.

Now, like others have mentioned, order does not have any mechanism to sanitize SQL, so you will have to use the protected class method on ActiveRecord::Base.

It may look like this:

order_sql = Category.send :sanitize_sql_array, ["CASE user_id WHEN ? THEN 1 ELSE 2 END", some_user_id]

@categories.order(order_sql)



回答2:


You can't do an ORDER BY user_id = <some_integer>. You can only order by a column ASC or DESC. There are some advanced cases that use the CASE keyword. Please read the mysql documentation.




回答3:


http://apidock.com/rails/ActiveRecord/QueryMethods/order

If you look at the source, it doesn't look like it does anything with the question marks, as compared to the where clause source code. http://apidock.com/rails/ActiveRecord/QueryMethods/where

Looking at GitHub too at the order method, nothing to do with the question marks: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/relation/query_methods.rb#L234




回答4:


You can encapsulate the where and the order method like this:

Model.where("user_id = ?", params[:id]).order("field_name DESC")

I think this should do it for you. I hope I understud it correctly.



来源:https://stackoverflow.com/questions/13802495/is-it-possible-to-use-question-marks-in-order-methods-clauses

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