Rails Active Record find(:all, :order => ) issue.
Posted
by CodingWithoutComments
on Stack Overflow
See other posts from Stack Overflow
or by CodingWithoutComments
Published on 2009-04-13T00:25:30Z
Indexed on
2010/04/28
10:53 UTC
Read the original article
Hit count: 188
I seem to be unable to use :order_by for more than one column at a time.
For example, I have a "Show" model with date and attending columns.
If I run the following code:
@shows = Show.find(:all, :order => "date")
I get the following results:
[#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
If I run the following code:
@shows = Show.find(:all, :order => "attending DESC")
[#<Show id: 4, date: "2009-04-21", attending: 136>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 7, date: "2009-04-18", attending: 2>]
But, if I run:
@shows = Show.find(:all, :order => "date, attending DESC")
OR
@shows = Show.find(:all, :order => "date, attending ASC")
OR
@shows = Show.find(:all, :order => "date ASC, attending DESC")
I get the same results as only sorting by date:
[#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
Where as, I want to get these results:
[#<Show id: 1, date: "2009-04-18", attending: 78>,
#<Show id: 7, date: "2009-04-18", attending: 2>,
#<Show id: 2, date: "2009-04-19", attending: 91>,
#<Show id: 3, date: "2009-04-20", attending: 16>,
#<Show id: 4, date: "2009-04-21", attending: 136>]
This is the query being generated from the logs:
[4;35;1mUser Load (0.6ms)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 1) LIMIT 1[0m
[4;36;1mShow Load (3.0ms)[0m [0;1mSELECT * FROM "shows" ORDER BY date ASC, attending DESC[0m
[4;35;1mUser Load (0.6ms)[0m [0mSELECT * FROM "users" WHERE ("users"."id" = 1) [0m
Finally, here is my model:
create_table "shows", :force => true do |t|
t.string "headliner"
t.string "openers"
t.string "venue"
t.date "date"
t.text "description"
t.datetime "created_at"
t.datetime "updated_at"
t.decimal "price"
t.time "showtime"
t.integer "attending", :default => 0
t.string "time"
end
What am I missing? What am I doing wrong?
UPDATE: Thanks for all your help, but it seems that all of you were stumped as much as I was. What solved the problem was actually switching databases. I switched from the default sqlite3 to mysql.
© Stack Overflow or respective owner