Displaying the last post item of each category
I have a ruby on rails application and i have two models posts and category. Category has_many :posts and Post belongs_to :catego开发者_C百科ry. Now how can i display the last post item of each category. i.e retrieving the last post in each category.
In your view something like:
<% @categories.each do |category| %>
<p><%= category.posts.last %></p>
<% end %>
the example above will order the records by id but you might want to order the result by "created_at" field (in case you have it):
<%= category.posts.order('created_at desc').last %>
精彩评论