'Order AR by enum and after, a random list
I have a user model with enum level and an each user has_many books
enum level: { member: 0, supporter: 1, pro: 3, partner: 4 }, _prefix: :level
I would like to display a books list with two orders :
Book.joins(:user).where(type: "fiction")
and to have in first place :
.where(user: { level: "partner"} )
and after, a randomize list for all other results
.where.not(user: { level: "partner"}
Solution 1:[1]
You can give ActiveRecord the .order(:columns)
and it will do them in order. Combine this with an order by case and you should have what you want. I'm not sure if your DB has knowledge of the enum, or if "4" will always remain the highest.
I.e. if "partner" will always be the highest enum (4)
Book.joins(:user).where(books: { type: "fiction" }).order('users.level DESC')
If you may add new ones and need to specify.
Book.joins(:user).where(type: "fiction").order('case when users.level = 4 then 0 else 1 end')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Ben Garcia |