fengd
fengd

Reputation: 7569

Rails Active Record Order Issue

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

Upvotes: 1

Views: 194

Answers (2)

joofsh
joofsh

Reputation: 1655

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.

Upvotes: 1

John Woo
John Woo

Reputation: 263723

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.

Upvotes: 3

Related Questions