简体   繁体   English

Rails遍历对象数组

[英]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. 但是我收到错误NoMethodError-未定义的方法`community_group_members',我想我没有按照我想要的方式正确地迭代@groups。

You should have: 你应该有:

user_ids << group.community_group_members.pluck(:member_id)

( group instead of @group ). group而不是@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 @ ). 这是因为在each块中,数组的元素是由局部变量(无前缀)而不是实例变量(由@前缀)表示的。 So @group instance variable is unset and thus evaluated to nil , which doesn't respond to community_group_members method. 因此,@ @group实例变量未设置,因此被评估为nil ,它不会响应community_group_members方法。

Also, I deleted your where clause, since it's reduntant - you're already doing this in group.community_group_members call. 另外,我删除了您的where子句,因为它是多余的-您已经在group.community_group_members调用中进行了此操作。

@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? 使用块变量组而不是@group是否有效?

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: 假设您有两个模型Community::GroupCommunity::GroupMember具有关联has_many :community_group_membersbelongs_to :community_group ,您的第一行是:

@groups = Community::GroupMember.where(:member_id => current_user.id)

returns an array of Community::GroupMember instances, ie group members , not groups. 返回的数组Community::GroupMember情况下,即组成员 ,而不是基团。

To get the associated groups you could use map : 要获取关联的组,可以使用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: 现在,您可以使用以下方法检索member_id

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM