0

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

Ie/

Posts.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).

1
  • look out for data where down = 0 of course Commented Apr 30, 2015 at 12:54

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I'm looking for doing math on multiple order bys, not just one field.
What does that mean? Give an example, please.
Example is in the original post. Post.order(up / down).all order by up column divided by down column.
Perfect!! I'm going to try this out again today - thank you!!
1
Post.order("created_at DESC").all
Post.order("title ASC").all

See here, for more details.

1 Comment

I'm looking for doing math on multiple order bys, not just one field.
0
Post.select("*, (up / greatest(down, 1)) as ratio").order("ratio asc")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.