![](/img/trans.png)
[英]In Rails, Using Mongoid, How do I find all Models with a valid (not nil) has_one reference?
[英]How do I get all the groups that have all the users I specified in an array in Rails/MongoId?
我有一個Groups
的集合,一個Users
的集合和一個GroupUsers
的集合,其中包含2個字段: group_id
和user_id
。 我想找到具有我在數組中指定的所有用戶的所有組。
例。 如果我做:
group1 << user1
group1 << user2
當我嘗試找到包含user1
, user2
和user3
,我應該沒有任何結果。 但是如果要包含user1
和user2
的組,我應該得到group1
。
我試過了:
GroupUser.where(:user.in => [user1, user3]).group_by(&:group)
但這將返回group1
因為user1
是該組的成員。
謝謝您的幫助。
我們終於找到了解決方案:
class Group
embeds_many :users, class_name: "GroupUser"
scope :with_status, -> (status) do
where(:"users.status" => status )
end
end
class User
end
class GroupUser
embedded_in :group
belongs_to :user
end
然后是Group.where(:"users.user_id".all => [user1.id, user2.id])
非常感謝您的幫助。
(僅適用於ActiveRecord):您可以在Group
類中同時使用having
和group
語句來定義此范圍:
class Group < ActiveRecord::Base
scope :with_all_users, ->(users) do
joins(:users)
.where(users: {id: users.map(&:id)})
.group('groups.id')
.having('count(users.id) = ?', users.size)
end
end
然后,您可以像這樣使用它來獲取具有您作為數組或集合提供的所有用戶的所有組:
Group.with_all_users([user1, user2, user3])
看起來您只需要使用all
而不是in
。 請參閱選擇文檔中的第一個條目。
可查詢#全部
添加$ all選擇。 文檔必須匹配數組中提供的所有值
queryable.all(field: [ 1, 2, 3 ])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.