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

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -