Muhammad Faisal Iqbal
Muhammad Faisal Iqbal

Reputation: 1836

rails sort by specifc order

I have model named Group which has users_count field in it.

I have to order groups based upon dynamic preference of users_count like [3,4,2] means show groups with 3 users_count first, than with 4 and than with 2

Right now, I am using 3 separate queries and than merge records like

groups = Group.where(users_count: 3)
         + Group.where(users_count: 4)
         + Group.where(users_count: 2)

It works but It don't make sense to use 3 separate queries.

How can I achieve this in single query?

Upvotes: 0

Views: 87

Answers (2)

Yakov
Yakov

Reputation: 3191

Since 3, 4, 2 is not a sequential order there should be a custom condition to order them properly you can do it by using the CASE WHEN expression.

order_sql = Arel.sql(
  'CASE WHEN users_count = 3 THEN 0 ' \
    'WHEN users_count = 4 THEN 1 ' \
    'ELSE 3 END'
)
Group.where(users_count: [2,3,4]).order(order_sql)

Which will give 0 when users_count = 3, 1 when users_count = 4, and 3 for other cases. With default ascending order you'll get the result you want.

Upvotes: 3

kykyi
kykyi

Reputation: 385

You can do

groups = Group.where(users_count: [3,4,2])

This will return the same groups as your 3 queries in a single query

Upvotes: -2

Related Questions