views:

156

answers:

2

Is there any way I can use the :limit and :order options in the find method. I'm trying to sort activities by descending order, such that the newest activities are shown. However, when I try to use the (:all, :limit => 5, :order=> 'Date desc) I get an error. I need to limit to only 5 records, and when I disregard the order option, it works but not what I need...

Thanks

+2  A: 

I think you missed a quote in your example.

Model.find(:all, :limit => 5, :order=> 'created_at desc')

Make sure that a date column exists in your table.

Kieran Hayes
I've tried this, but I get this errorAn expression in the ORDER BY clause in the following position, or starting with "DATE" in the "ORDER BY" clause is not valid. Reason code = "2". SQLSTATE=42822
It might not be called "Date". Try "date", "created_at" or "updated_at".
dylanfm
A: 

Is your date column actually called date? First, I would change that, date is the name of a function in most databases, that could be the cause of the error you are seeing. Rails uses created_at, updated_at, etc, so following that naming scheme will make your code more readable to future maintainers.

You could try to quote the column name in back-ticks:

:order => "`date` desc"
Michael Sepcot
Unfortunately, the issue isn't with regards to the date column, it works perfectly when I do not use the :limit option, it does sort by date descending. I know the column name isn't desirable, but it cannot be changed now. The limit option works when I use it without the order option and vice versa
Can you post the log of what SQL is trying to be executed?
Michael Sepcot