asdfkjasdfjk
asdfkjasdfjk

Reputation: 3904

Rails iterate over objects array

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

Answers (3)

Stefan
Stefan

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

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

Upvotes: 0

BWStearns
BWStearns

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

Marek Lipka
Marek Lipka

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

Related Questions