用OR来循环for循环 [英] For loop within for loop with OR

查看:173
本文介绍了用OR来循环for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想返回我的帖子和我的followed_users帖子。



我有一个名为followed_users的关联,所以我可以给current_user中的朋友打电话@ user.followed_users

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

这只适用于followed_users的帖子。我也想包括我的帖子。所以我的计划是首先检查我的帖子,然后遍历所有看到哪些属于我的followed_users。

我的实现返回我的帖子,但不是所有followed_users

p>

我在正确的轨道上吗?

 < Post.all%> 
<%如果post.user_id == current_user.id ||
为current_user.followed_users中的朋友
为friends.posts中的帖子
结束
结束%>
< li>
<%= post.user.name%>
<%= post.body%>
< / li>
<%end%>
<%end%>


解决方案

不要,真的不要这样做,不能负责循环所有的对象。



执行此操作:

  #in部分,例如_post_details.html.erb 
< li>
<%= post.user.name%>
<%= post.body%>
< / li>

在您的主视图中:

 <%current_user.followed_users.each do | friend | %GT; 
<%=渲染部分:post_details,集合:friend.posts,如::post%>
<%end%>

<%=渲染部分:post_details,集合:current_user.posts,如::post%>

顺便说一句,要小心 N + 1 查询(followers - > posts)。




在您发表评论后,我建议您这样做:


$ b $

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

然后在您的视图中:

 <%=渲染部分:post_details,集合:@posts,如::post%> 


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

解决方案

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

这篇关于用OR来循环for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆