简体   繁体   中英

Rails 4 One query for select users from workspace with specific role (has_many through)

I have following models:

class Workspace < ActiveRecord::Base
...
  has_many :workspaces_memberships, :dependent => :destroy
  has_many :users, :through => :workspaces_memberships
  has_many :roles, :through => :workspaces_memberships
...
end

class WorkspacesMembership < ActiveRecord::Base
  belongs_to :user
  belongs_to :workspace, touch: true
  belongs_to :role
...
end

I want to select all users from workspace , who have role admin ( role_id 1 , but it would be brilliant to search it by name in Role model) in one query (in WorkspacesMembership model I have user_id , workspace_id , role_id ).

Any suggestions?

尝试这个:

Workspace.joins(:roles).where('roles.name = ?', "admin")

I would try this :

Workspace.joins(:roles).merge(Role.where(:name=>"admin"))

joins and includes used with merge are very powerful for complex requests.

Check if you want an INNER JOIN (joins) or a LEFT OUTER JOIN (includes).

EDIT : As pointed by Surya I misread the question.

Here is a query to get all admin users of workspace_instance :

workspace_instance.users.joins(:roles).merge(Role.where(:name=>"admin"))

It implies that User have has_many :roles, :through => :workspaces_memberships

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM