Reputation: 3904
I want to do something like this
@groups = Community::GroupMember.where(:member_id => current_user.id)
user_ids = []
@groups.each do |group|
user_ids << @group.community_group_members.where(:group_id => group.id).pluck(:member_id)
end
But I get error NoMethodError - undefined method `community_group_members' I think im not iterating @groups properly the way I want.
Upvotes: 1
Views: 434
Reputation: 114258
Assuming you have two models Community::Group
and Community::GroupMember
with associations has_many :community_group_members
and belongs_to :community_group
respectively, your first line:
@groups = Community::GroupMember.where(:member_id => current_user.id)
returns an array of Community::GroupMember
instances, i.e. group members, not groups.
To get the associated groups you could use map
:
@group_members = Community::GroupMember.where(member_id: current_user.id)
@groups = @group_members.map { |group_member| group_member.community_group }
or a join:
@groups = Community::Group.joins(:community_group_members).where(community_group_members: { member_id: current_user.id })
You can now retrieve the member_id
s with:
user_ids = Community::GroupMember.where(group_id: @groups).pluck(:member_id)
Upvotes: 0
Reputation: 2706
@groups = Community::GroupMember.where(:member_id => current_user.id)
user_ids = []
@groups.each do |group|
user_ids << group.community_group_members.where(:group_id => group.id).pluck(:member_id)
end
Does using the block variable group instead of @group work?
Upvotes: 0
Reputation: 51191
You should have:
user_ids << group.community_group_members.pluck(:member_id)
(group
instead of @group
). It's because inside each
block, the element of your array is represented by local variable (which is unprefixed) instead of instance variable (prefixed by @
). So @group
instance variable is unset and thus evaluated to nil
, which doesn't respond to community_group_members
method.
Also, I deleted your where
clause, since it's reduntant - you're already doing this in group.community_group_members
call.
Upvotes: 2