Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you order by a custom model method that has no attribute in SQL?

Previously I ordered my posts as this:

@posts = Post.find(:all, :order => "created_at DESC") 

But now I want to replace created_at with a custom method I wrote in the Post model that gives a number as its result.

My guess:

@posts = Post.find(:all, :order => "custom_method DESC") 

which fails..

like image 448
Trip Avatar asked Oct 29 '10 20:10

Trip


1 Answers

It fails because you are asking your db to do the sorting.

@posts = Post.all.sort {|a,b| a.custom_method <=> b.custom_method}

Note that this becomes non-trivial when you want to start paging results and no longer wish to fetch .all. Think about your design a bit before you go with this.

like image 156
jdl Avatar answered Oct 14 '22 11:10

jdl