Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through an activerecord::relation array

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"]
like image 920
Simpleton Avatar asked Jan 30 '26 07:01

Simpleton


1 Answers

comments = @males.map {|user| user.comments.map(&:content)}.flatten
like image 99
Mori Avatar answered Feb 01 '26 23:02

Mori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!