list post in categories
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.开发者_如何学JAVA
Want I need is
Category Name
- Post1
- Post2
- Post3
Category Name2
- Post1
- Post2
- Post3
etc...
Thanks
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 %>
精彩评论