0

I am trying to display just the last post for each user and having messed around for a while, I cannot work it out.

I have relationships of users has many posts and posts belong to users. When I use the below code it correctly puts each users email address but it puts the value for each post as the last overall value (not the last value for that specific user).

<% @users.each do |u| %>
  <%= @posts.last.total %>
  <%= u.email %>
<% end %>

(Total is a calculation performed in posts model and saved in the db.)

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79

2 Answers2

0

you may try this code, change @posts to u.posts

<% @users.each do |u| %>
  <% if u.posts.size > 0 %>
    <%= u.posts.last.total %>
    <%= u.email %>
  <% end %>      
<% end %>
widjajayd
  • 6,090
  • 4
  • 30
  • 41
  • Thanks @widjajayd I tried this but it comes up with an error undefined method `total' for nil:NilClass. I know this normally happens when there is nothing in the field for a particular, but I have checked the posts and they all have a value? – Matt Hardman Jul 12 '17 at 14:59
  • meaning one of the user do not have any post, let me edit my code to check it – widjajayd Jul 12 '17 at 15:04
  • Ah yes you are correct 2 users don't have any posts. How do I change it so it ignores users who have no posts? – Matt Hardman Jul 12 '17 at 15:09
  • I just edited the code so if the user has posts (.size > 0) it will print it, if not then it will skip to next user – widjajayd Jul 12 '17 at 15:11
  • You should be able to get only users with post(s) using `User.joins(:posts)` instead of `User.all` (see [this answer](https://stackoverflow.com/a/38440584/6231376)). – TeWu Jul 12 '17 at 15:13
  • Ouch n+1. @MattHardman consider eager loading the posts (still inefficient but better) or creating a scope for the most recent post and merging that into the user query. – engineersmnky Jul 12 '17 at 15:37
0

If you have more than a trivial number of users and posts then I would consider trying to reduce the number of queries you're issuing.

You can very quickly get the maximum post_id per user_id ...

max_post_id_per_user = Post.group(:user_id).maximum(:id)

... and get a hash of the required Posts ...

max_post_per_user = Post.where(id: max_post_id_per_user).group_by(:user_id)

... and then reference that hash to get the required post for the user id.

David Aldridge
  • 51,479
  • 8
  • 68
  • 96