I have a ticket model which has a method inside called closes_in
that calculates the time left from the DB field start_date:date
to now. Currently my find query is:
@tickets = Ticket.find(:all,
:origin => @user.coords,
开发者_StackOverflow社区 :order => 'distance',
I can't just put in closes_in as I get an error. How do I make it so I can use closes_in
to sort the query if it's a method and not an actual field in the DB?
Use the sort_by method:
@tickets = Ticket.find(:all, :conditions => "foo").sort_by { |t| t.closes_in }
If you are using MySQL:
@tickets = Ticket.all(:order => "DATEDIFF(CURDATE(), start_date)")
If you are using PostgreSQL:
@tickets = Ticket.all(:order => "AGE(start_date)")
This way you are using DB for sorting. Sorting using ruby should be restricted to a small data-set that is guaranteed to remain small.
精彩评论