Pita Pita - 5 months ago 9
Ruby Question

Querying for Objects that contains some object in a one to many relationship

So I have two models

class User
has_many :roles
end

class Role
belongs_to :user
end


how would I query for "who has xxx-role?"
thank you,

Answer

Start off my making a roles query

roles = Role.where(some_key: some_val).includes(:user)

You tack on the includes here to preload the associated user records. This way, you can get the users like so:

roles.map(&:user) which is equivalent to roles.map { |role| role.user }.

It would work without the includes but it would be slower. This is because of the N+1 sequel issue.