且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ruby on Rails:按月分组博客帖子

更新时间:2023-01-29 21:01:42

group_by是一个很好的方法:



控制器:

  def archive 
#this将返回一个哈希,其中月份名称是键
#,值为属于这些月份的帖子的数组
#something like:
#{February=> [#< Post 0xb5c836a0>,#< Post 0xb5443a0>],
#'March'=> [#< Post 0x43443a0>]}
@posts_by_month = Posts.find(:all).group_by {| post | post.created_at.strftime(%B)}
end

查看模板: / p>

 <%@ posts_by_month.each do | monthname,posts | %GT; 
<%= monthname%>
< ul>
<%posts.each do | post | %GT;
< li><%= post.title%>< / li>
<%end%>
< / ul>
<%end%>


Hy guys. I've created a simple blog app with the usual CRUD actions. I've also added a new action in the PostController called "archive" and an associated view. In this view I want to bring back all blog posts and group them by month, displaying them in this kind of format:

March
<ul>
    <li>Hello World</li>
    <li>Blah blah</li>
    <li>Nothing to see here</li>
    <li>Test post...</li>
</ul>

Febuary
<ul>
    <li>My hangover sucks</li>
    ... etc ...

I can't for the life of me figure out the best way to do this. Assuming the Post model has the usual title, content, created_at etc fields, can someone help me out with the logic/code? I'm very new to RoR so please bear with me :)

group_by is a great method:

controller:

def archive
  #this will return a hash in which the month names are the keys, 
  #and the values are arrays of the posts belonging to such months
  #something like: 
  #{ "February" => [#<Post 0xb5c836a0>,#<Post 0xb5443a0>],
  # 'March' => [#<Post 0x43443a0>] }
  @posts_by_month = Posts.find(:all).group_by { |post| post.created_at.strftime("%B") }
end

view template:

<% @posts_by_month.each do |monthname, posts| %>
<%= monthname %>
<ul>
   <% posts.each do |post| %>
     <li><%= post.title %></li>
   <% end %>
</ul>
<% end %>