For loop within for loop with OR

大憨熊 提交于 2020-01-16 05:26:05

问题


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 %>


来源:https://stackoverflow.com/questions/19123112/for-loop-within-for-loop-with-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!