Reputation: 15156
Let say I have a Group
of User
s and User
has a enum, which described it's mood.
class Group < AR::Base
has_many :users
class User < AR::Base
belongs_to :group
enum mood: %i(good bad ugly)
How can I find all groups, where at least one User
has the good mood?
Which index should I add for optimizing this query?
Upvotes: 3
Views: 140
Reputation: 118271
You can use joins
method.
Group.joins(:users).where("users.mood = ?", User.moods[:good])
You can add this into your migration
add_index :users, :group_id
Upvotes: 1