1

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.

1
  • Are you receiving any data back from your Community::GroupMember.where(:member_id => current_user.id) call? Commented Mar 6, 2014 at 10:23

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
@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?

Comments

0

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_ids with:

user_ids = Community::GroupMember.where(group_id: @groups).pluck(:member_id)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.