rails 2.3.4, sqlite3
I'm trying this
Production.find(:all, :conditions => ["time > ?", start_time.utc], :order => "time DESC", :limit => 100)
The condition works perfectly, but I'm having problems with the :order => time DESC.
By chance, I discovered that it worked at Heroku (testing with heroku console), which runs PostgreSQL. However, locally, using sqlite3, new entries will be sorted after old ones, no matter what I set time to. Like this (output has been manually stripped): second entry is new:
Production id: 2053939460, time: "2010-04-24 23:00:04", created_at: "2010-04-24 23:00:05"
Production id: 2053939532, time: "2010-04-25 10:00:00", created_at: "2010-04-27 05:58:30"
Production id: 2053939461, time: "2010-04-25 00:00:04", created_at: "2010-04-25 00:00:04"
Production id: 2053939463, time: "2010-04-25 01:00:04", created_at: "2010-04-25 01:00:04"
Seems like it sorts on the primary key, id, not time. Note that the query works fine on heroku, returning a correctly ordered list! I like sqlite, it's so KISS, I hope you can help me...
Any suggestions?
UPDATE/SOLVED:
time is a reserved sqlite3 keyword (date, amongst others, is too). This is why :order => 'time DESC'
works in PostgreSQL (non-reserved keyword), but not in sqlite3. The solution is to avoid having sqlite3 keywords as column names if you ever intend to sort on them. Renaming solves the problem.
I've tested with the standard rails pattern updated_at and created_at, which works perfectly.
I still prefer sqlite3 in development, it's so simple and smooth to work with, copy the database and send to your partner. Thanks to @newtover !
It is usually a bad idea to use reserved words without surrounding quotes. time
is a built-in function in SQLite, try using the following instead and better get rid of the ambiguity in the first place:
Production.find(:all,
:conditions => ["`time` > ?", start_time.utc],
:order => "`time` DESC",
:limit => 100)
UPD: The problem seems to have appeared on SO:
来源:https://stackoverflow.com/questions/2719941/sqlite3-activerecord-order-time-desc-doesnt-sort