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, ...
If you are trying to change the order based on the
user_id, returning those that match first, you should be using aCASEstatement.In raw SQL, it would look like this:
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,
orderdoes not have any mechanism to sanitize SQL, so you will have to use the protected class method onActiveRecord::Base.It may look like this: