Alex Antonov
Alex Antonov

Reputation: 15156

rails has_many at least one children has the value

Let say I have a Group of Users 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

Answers (1)

Arup Rakshit
Arup Rakshit

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

Related Questions