views:

37

answers:

1

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

+1  A: 

I would do something like:

class User < ActiveRecord::Base
   has_many :posts
   has_many :categories, :through => :posts, :uniq => true
end

class Post < ActiveRecord::Base
   belongs_to :user
end

class Category < ActiveRecord::Base
   has_many :posts
end

# controller
@categories = current_user.categories

# view
<% @categories.each do |category| %> 
  <%= category.name %><br/> 
  <% category.posts.select {|post| post.user==current_user}.each do |post| %> 
    <%= post.content %><br/> 
  <% end %> 
<% end %> 
j.
Hey J,Thanks for the comment - after doing that, the @categories duplicated categories for each user. i.e. If a user posted twice in business, and 3 times in movies.The @categories var stores:businessbusinessmoviesmoviesmoviesany idea how to avoid this?
Elliot
You must add `, :uniq => true` to the `has_many :through`. See http://blog.hasmanythrough.com/2006/5/6/through-gets-uniq for details.
egarcia
@Elliot: as egarcia said, there was a `:uniq => true` missing... Now it works without the duplicated categories :]
j.
@egarcia: you're right! tks for that ;]
j.
@j: no problem! It was fun :)
egarcia
Thanks so much guys! I can't even explain how much this helped!
Elliot