开发者

Sorting a "Find" using methods rather than fields in the database

开发者 https://www.devze.com 2023-01-07 20:53 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消