2

How can I iterate through an array of Activerecord::Relation objects? For instance, let's say I have a Comment class and a User class and I'd like to get all the comment contents from 3 specific users (assuming comments belong to users and user_id is the foreign key):

>> @males = Comment.where('user_id IN (?)', ["123","456","789"])
=> [...] #Array of comment Activerecord::Relation objects

Now I'd like to iterate through comments_from_males and collect all the content attribute contents for each comment in the array.

To clarify, the following works but only for the first male returned, but I need all the comments for all males:

>> @males.first.comments.map(&:content)
=> ["first comment", "second comment"]

3 Answers 3

7
comments = @males.map {|user| user.comments.map(&:content)}.flatten
Sign up to request clarification or add additional context in comments.

Comments

1
Comment.where('user_id IN (?)', ["123","456","789"]).pluck(:content)

The method pluck

2 Comments

Activerecord::relation objects don't have a pluck method available to them.
Example from documentation - Person.where(:confirmed => true).limit(5).pluck(:id)
1

You can use

comments_from_males = @males.collect{|e| e.content if e.gender == "male"}.flatten

It will give you list of all comments from males. Check my db assumptions match.

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.