Remaking this loop by user?
Posted
by Elliot
on Stack Overflow
See other posts from Stack Overflow
or by Elliot
Published on 2010-05-20T23:49:49Z
Indexed on
2010/05/21
0:20 UTC
Read the original article
Hit count: 400
ruby-on-rails
I'm wondering if theres a best practice for what I'm trying to accomplish...
First we have the model categories, categories, has_many posts.
Now lets say, users add posts.
Now, I have a page, that I want to display only the current user's posts by category.
Lets say we have the following categories: A, B, and C
User 1, has posted in Categories A and B.
In my view I have something like:
<% @categories.select {|cat| cat.posts.count > 0}.each do |category| %>
<%= category.name %><br/>
<% category.posts.select {|post| post.user == current_user}.each do |post| %>
<%= post.content %><br/>
<% end %>
<% end %>
For the most part its almost there. The issue is, it will still show an empty category if any posts have been entered in it at all (even if the current user has not input posts into that category.
So the question boils down to:
How do I make the following loop only count posts in the category from the current user?
<% @categories.select {|cat| cat.posts.count > 0}.each do |category| %>
Best, Elliot
© Stack Overflow or respective owner