views:

27

answers:

1

I have a a post model and a categories model

I want to show a list the all posts by category all on one page.

I am using has and belong_to in each model correctly.

I just cant fiqure out how to show them in my view.

Want I need is

Category Name

  • Post1
  • Post2
  • Post3

Category Name2

  • Post1
  • Post2
  • Post3

etc...

Thanks

+3  A: 

In your controller set @categories:

@categories = Category.find(:all, :include => :posts) # you may specify your conditions here
# :include is needed to avoid a query on each "category.posts" call later in the view

Then in the view:

<% for category in @categories %>
  <strong><%= category.name %></strong>
  <ul>
    <% for post in category.posts %>
      <li><%= post.name %></li>
    <% end %>
  </ul>
<% end %>
Sergei Kozlov
You could also use the `group_by` method on `Enumerable` for the view code. http://api.rubyonrails.org/classes/Enumerable.html#M002570
samg
I'd add :include => :posts to the Category.find call to eliminate the n+1 query problem. The version here will work, but it will hit the database for each category to get it's posts. Using :include causes ActiveRecord to do a join when it generates the SQL query.
madlep
@madlep, that's true, thanks, editing the answer
Sergei Kozlov
Awesome Thanks that is what i needed
Fresh
@Fresh, please, tick off those answers that provide the solution to your questions as "accepted" - it will keep your "acceptance rate" high, and will reward those users that give the solution (in order to do it, click the tick mark on the left from the answer).
Sergei Kozlov