我有以下情况,似乎在Rails中应该很容易,但它正在逃避我。可以说我有以下多对多的关系。用户和组(组是用户通过'成员资格'所属的东西):
Class User < ActiveRecord::Base
has_many :groups, through: :memberships
end
Class Membership < ActiveRecord::Base
belongs_to :users
belongs_to :groups
end
Class Group < ActiveRecord::Base
has_many :users, through: :memberships
end
所以现在我做了一个选择多个组的查询(所以我会得到一组例如在东北地区的组。这样的事情:
northeast_groups = Group.where("region = 'northeast'")
现在我想做的是这样的事情:
northeast_groups.users.count
或者更好的是,像这样:
northeast_groups.users.each do |u|
遍历所选组的所有用户。
有没有办法在Rails中执行此操作?
答案 0 :(得分:1)
你可以这样做:
User.includes(:groups).where(groups: { region: 'northeast' })
<强>注意:强>
您必须在includes
和joins
中使用关系名称,但必须在where
子句中使用确切的表名:
User has_many :posts
# ^^^^^
Post belongs_to :user
# ^^^^
User.includes(:posts).where(posts: { title: 'Little bobby table' })
# ^^^^^ ^^^^^
Post.includes(:user).where(users: { username: 'Bob' })
# ^^^^ ^^^^^