Rails many to many -
i have following situation seems should easy in rails it's escaping me. lets have following many many relationship. user , groups (group being user belongs through 'membership'):
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
so query selects more 1 group (so array of groups were, example, in northeast region. this:
northeast_groups = group.where("region = 'northeast'")
now this:
northeast_groups.users.count
or better yet, this:
northeast_groups.users.each |u|
to loop through of users selected groups.
is there way in rails?
you can this:
user.includes(:groups).where(groups: { region: 'northeast' })
attention:
you have use relation's name in includes
, joins
, have use exact table's name in where
clause:
user has_many :posts # ^^^^^ post belongs_to :user # ^^^^ user.includes(:posts).where(posts: { title: 'little bobby table' }) # ^^^^^ ^^^^^ post.includes(:user).where(users: { username: 'bob' }) # ^^^^ ^^^^^
Comments
Post a Comment