开发者

Displaying the last post item of each category

开发者 https://www.devze.com 2023-02-16 09:39 出处:网络
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 catego

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

精彩评论

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