开发者

Complex Order By Queries using Rails 3.0 + Postgres

开发者 https://www.devze.com 2023-02-17 10:15 出处:网络
Does rails have any way to have complex sorting at the database query level? Ie/ Post开发者_如何学Cs.order(up / down).all ?

Does rails have any way to have complex sorting at the database query level?

Ie/

Post开发者_如何学Cs.order(up / down).all ?

What would be the best way to implement this on a database level (in postgres) without having to sort through a result in ruby using sort (which will slow down pagination etc).


If you use the wonderful meta_where gem, you can also do something like

Post.order(:create_at.asc)

To sort by a function of two or more columns you can do something like

Post.select("*, (up / down) as ratio").order("ratio asc")

You will have what you want and moreover every Post object in that array will have a ratio method for you to know the exact value.


Post.order("created_at DESC").all
Post.order("title ASC").all

See here, for more details.


Post.select("*, (up / greatest(down, 1)) as ratio").order("ratio asc")
0

精彩评论

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

关注公众号