【问题标题】:For loop within for loop with OR带有 OR 的 for 循环内的 for 循环
【发布时间】:2013-10-08 00:31:19
【问题描述】:

我有点卡住了。

我想退回我的帖子和我的 follow_users 帖子。

我有一个名为“followed_users”的关联,所以我可以调用@user.followed_users

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

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

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

我走对了吗?

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

【问题讨论】:

    标签: ruby-on-rails ruby loops for-loop iteration


    【解决方案1】:

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

    这样做:

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

    在您的主视图中:

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

    顺便说一句,注意很可能出现的N+1 查询(关注者 -> 帖子)。


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

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

    那么在你看来:

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

    【讨论】:

    • 您好,感谢您的意见。我试图将结果保留在一个电话中,因此订购/排序会更容易。例如。)对 current_user.posts 和friend.posts 进行排序,并按第一次创建排序。
    • 嘿,一个后续问题。 ids = current_user.followed_users.map(&:id) + [ current_user.id ] posts = Post.where(user_id: ids) 当它们来自同一模型时,它们可以完美地工作。但是,如果它们来自不同的型号,你建议我如何处理。我试图 b.created_at } %> 但是当我尝试迭代时,它们的不同属性会导致问题
    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2015-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    相关资源
    最近更新 更多