0

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?

Eyeslandic
  • 14,553
  • 13
  • 41
  • 54
Muhammad Faisal Iqbal
  • 1,796
  • 2
  • 20
  • 43

2 Answers2

3

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.

Yakov
  • 3,033
  • 1
  • 11
  • 22
-2

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

kykyi
  • 375
  • 4
  • 10