Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop through 2 model objects at once rails

I have a users object that I'm exposing through the simple call:

@users = User.all

I also have some more expensive queries I'm doing where I'm using custom SQL to generate the results.

@comment_counts = User.received_comment_counts

This call and others like it will return objects with one element per user in my list ordered by id.

In my view I'd like to loop through the users and the comment_counts object at the same time. Eg:

for user, comment_count in @users, @comment_counts do
end

I can't figure out how to do this. I also can't seem to figure out how to get an individual record from the @comment_counts result without running it through @comment_counts.each

Isn't there some way to build an iterator for each of these lits objects, dump them into a while loop and step the iterator individually on each pass of the loop? Also, if you can answer this where can I go to learn about stepping through lists in rails.

like image 321
walta Avatar asked Dec 28 '22 17:12

walta


2 Answers

Something like this should work for you:

@users.zip(@comment_counts).each do |user, comments_count|
  # Do something
end

I've never come across manual manipulation of iterators in Ruby, not to say that it can't be done. Code like that would likely be messy and so I would likely favor more elegant solutions.

like image 140
Wizard of Ogz Avatar answered Jan 05 '23 13:01

Wizard of Ogz


Assuming the arrays have equal values:

In your controller:

@users = User.all
@comments = Comment.all

In your view.

<% @users.each_with_index do |user, i |%>
    <% debug user %>
    <% debug @comments[i] %>
<% end %>

Then you can just check if the values exists on @comments if you don't know if the arrays have the same number of objects.

like image 30
thenengah Avatar answered Jan 05 '23 11:01

thenengah