Pita Pita - 4 months ago 6x
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

class Role
belongs_to :user

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


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.