Jean
Jean

Reputation: 5411

MongoId rails3, get inner array elements

I have 2 Models, Kid and friend_list. To the the kid I use:

k = Kid.where(email: "[email protected]").first

Then, to get the friend list I type:

k.friend_list

and I get:

[#<FriendList _id: 5305cb6485216d2689004785, _type: nil, name: "Friends", members: ["5374a1f320db90054c0000ea", "537c63ea20db9040d2000332"], kid_id: BSON::ObjectId('5305cb6285216d2689004742'), teacher_id: nil>]

But I only need the "members".

I tried

k.friend_list.members, but I get

NoMethodError: undefined method `members' for
#<Array:0x007fcf4b013138> from /Users/jeanosorio/.rvm/gems/ruby-1.9.3-p484@blabloo/gems/mongoid-2.8.1/lib/mongoid/criteria.rb:387:in
`method_missing'

How can I get only the members array??

Thanks in advance.

Upvotes: 0

Views: 50

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37419

It seems that friend_list returns an Array of FriendList.

You can create a new list composed of the values of the members getter using map:

k.friend_list.map(&:members)
# => [["5374a1f320db90054c0000ea", "537c63ea20db9040d2000332"]]

Or, alternatively, if you only meant to have a single FriendList per Kid, you should change your model to a single FriendList object.

For the current model, you can also do:

k.friend_list.first.members
# => ["5374a1f320db90054c0000ea", "537c63ea20db9040d2000332"]

Upvotes: 1

Related Questions