For loop within for loop with OR

2019-08-09 16:37发布

问题:

I'm a bit stuck.

I want to return my posts and my followed_users posts.

I have a association called "followed_users" so I am able to call @user.followed_users

<% for friends in current_user.followed_users  %>
 <% for post in friends.posts %>
  <%= post.body %>
 <% end %>
<% end %>

This works, however only for "followed_users" posts. I also want to include my posts. So my plan is first check for my post then loop through all to see which belongs to my followed_users.

My implementation is returning my post but not all of followed_users.

Am I on the right track?

<% for post in Post.all %>
 <% if post.user_id == current_user.id ||
   for friends in current_user.followed_users
    for post in friends.posts
    end
  end %>
   <li>
    <%= post.user.name %>
    <%= post.body %>
   </li>
 <% end %>
<% end %>         

回答1:

Dont, really don't do this, you cannot afford looping all your objects.

Do this:

#in a partial, say _post_details.html.erb
<li>
  <%= post.user.name %>
  <%= post.body %>
</li>

In your main view:

<% current_user.followed_users.each do |friend|  %>
   <%= render partial: "post_details", collection: friend.posts, as: :post %>
<% end %>

<%= render partial: "post_details", collection: current_user.posts, as: :post %>

Btw, beware of the very likely N+1 query (followers -> posts).


After your comment, I suggest you to do:

ids = current_user.followed_users.map(&:id) + [ current_user.id ] 
@posts = Post.where(user_id: ids)

Then in your view:

<%= render partial: "post_details", collection: @posts, as: :post %>