0
在我寫的應用程序中,我有可能屬於任何組數的用戶。通過相應的group_membership模型存在has_many關係。高效過濾多對多
我正在使用報告界面,並希望按組進行過濾,因此我想返回屬於所有列出組的用戶(即使他們屬於其他附加組)。
目前,我反覆根據用戶的成員資格向每個組依次過濾一組用戶,以便在用戶不是當前組的成員時過濾掉用戶。
@users = @account.users.joins(:groups).where("groups.id in (?)",all_groups).pluck('users.id') #All user IDs
positions_users = @account.users.joins(:groups).where("groups.id in (?)",positions).pluck('users.id') unless positions.empty?
departments_users = @account.users.joins(:groups).where("groups.id in (?)",departments).pluck('users.id') unless departments.empty?
locations_users = @account.users.joins(:groups).where("groups.id in (?)",locations).pluck('users.id') unless locations.empty?
miscellaneous_users = @account.users.joins(:groups).where("groups.id in (?)",miscellaneous).pluck('users.id') unless miscellaneous.empty?
@users = @users.select {|x| positions_users.include? x } unless positions_users.nil? || positions_users.empty?
@users = @users.select {|x| departments_users.include? x } unless departments_users.nil? || departments_users.empty?
@users = @users.select {|x| locations_users.include? x } unless locations_users.nil? || locations_users.empty?
@users = @users.select {|x| miscellaneous_users.include? x } unless miscellaneous_users.nil? || miscellaneous_users.empty?
有沒有更有效的方法呢?
你可以發佈一些示例代碼? – PinnyM
當然,有編輯問題。 – apchester