开发者

Sorting activerecord objects in Rails 3

开发者 https://www.devze.com 2023-02-01 01:45 出处:网络
I have a Post model that has_one Status.I want to sort the objects wherein those with a Post.status.description == \'in process\'are first, followed by those with status \'pending\', followed by \'act

I have a Post model that has_one Status. I want to sort the objects wherein those with a Post.status.description == 'in process' are first, followed by those with status 'pending', followed by 'active', with each sorted internally by Post.created_at. Any ideas about how one might do this would be much appreciated.

One wrinkle: I am trying to make this work with will paginate like so:

posts.paginate(:page => page, :per_page=>10, :order=>"#{sort_by} #{direction}")

So unfortunately it looks like I'll have to fit the logic into the order开发者_StackOverflow社区 parameter.

Thanks


It might be best to refactor the statuses into a domain table that has a sort attribute. Then you would join from posts to statuses and sort by statuses.sort_order.

If you don't want to do that and you don't mind mixing in a little sql, you could use a case statement like:

:order => "case when status = 'in process' then 1 when status = 'pending' then 2 else 3 end, created_at, created_at"

That works on MySQL; check your database for exact syntax. There might be a performance hit on very large tables, although probably minimal if status is indexed.

0

精彩评论

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