I have a model class named Event, and a field 'when'. I'm trying to return events order by when desc, so here is the code.
@events = Event.order("'when' DESC")
I'm using MySQL as the database. but the returned results is not sorted .
I've looked into the console, and file the generated sql, which seems ok
SELECT `events`.* FROM `events` ORDER BY 'when' DESC
and I also run this sql in console, and it returned sorted result. Is anything special with 'when'?
if I changed my query to Event.order("events.when DESC")
, then it returned a sorted result
it should be backtick, not single quote.
@events = Event.order("`when` DESC")
when you use single quote
around when
it is not a column anymore but merely a string value. you should have use backtick instead of single when escaping tableName and columnName.
You can remove the single quotes you are adding to the field. It should work with quotes around the whole thing such as:
@events = Event.order("column_name DESC")
This is true in general for column_names, except in your case where when
is a reserved word. So you then need to backtick it:
@events = Event.order("`when` DESC")
But still, I'd recommend changing your column name, you'll eventually run into complications using a reserved word. when
is also not very descriptive in my opinion, is it: When the event was created/ordered? When the event will begin? When the event will end? Perhaps a occurring_at
or date_occurring
column name would be more detailed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.