开发者

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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜