1

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 %>         
RedRory
  • 632
  • 1
  • 6
  • 18

1 Answers1

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 %>
apneadiving
  • 114,565
  • 26
  • 219
  • 213
  • Hey, Thanks for your input. I was trying to keep the result in one call, so it would be easier to order/sort. eg.) To sort through both current_user.posts and friend.posts and sort by first created. – RedRory Oct 01 '13 at 19:39
  • Hey, a follow up question. ids = current_user.followed_users.map(&:id) + [ current_user.id ] posts = Post.where(user_id: ids) Works perfectly, when they are from the same model. However how you recommend I tackle if they are from different models. I tried to <% post_and_events = posts + current_user.events.sort{|a,b| a.created_at <=> b.created_at } %> however their different attributes causes problems when I'm trying to iterate through – RedRory Oct 02 '13 at 03:11