Вопрос

I have two objects

class User
  ...
  has_many :roles
end

class Role
  ...
  belongs_to :user
end

I can assign roles to users without a problem. However, I want to be able to query for all users that have a particular role. This should be incredibly simple. However, I seem to be incapable of getting results.

I would think something like this should work:

role = Role.first
u = User.first
u.roles << role
u.save
User.in(role_ids: role._id)

However, it returns nothing. The role is successfully assigned to the user, but I can't figure out how to query for all users with specific role. I know it has to be simple, but I am driving myself crazy trying to figure it out.

Это было полезно?

Решение

Nevermind. I should've been using has_and_belongs_to_many instead of "has_many" and "belongs_to" since many users can share a role. Indeed it was a very simple solution, I was just going about it all wrong. Once I changed the relationship to has_and_belongs_to_many, I can just say "role.users" to get a list of all users with that role.

Другие советы

You need use "many to many relationships" between "User" and "Role".

class User
  include Mongoid::Document
  has_and_belongs_to_many :roles
end

class Role
  include Mongoid::Document
  has_and_belongs_to_many :users
end

Then you can use "role.users" to get the user list. And if you have any questions, you can read mongoid document: http://mongoid.org/en/mongoid/docs/relations.html#has_and_belongs_to_many .

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top