按月/年红宝石显示帖子 [英] display posts by month/year ruby
问题描述
不确定从何处开始,所以这里开始。.我正在建立一个小博客,在其中显示每个帖子的日期,加班每个月会有很多博客帖子,我希望将这些帖子分组在一起
Not sure where to start with this so here goes.. I am building a small blog in which the date of each post is displayed, overtime there will be many blog posts per month, for which i would like to group together by the month it was published.
我想在视图中这样显示它
I want to display it like this in the view
Archives
January 2013
February 2013
March 2013
etc
当我单击给定月份时,想法是将带我到该月内发布的所有帖子。
When i click on a given month the idea is it will take me to all the posts that where published within that month.
到目前为止,我可以按月份和年份对所有帖子进行分组
So far I can group all the posts by month and year
@posts_by_month = Post.all.group_by { |post| post.created_at.strftime("%B %Y") }
然后在我看来
<% @posts_by_month.each do |m| %>
<%= m %>
<% end %>
在视图中返回哪个
["July 2013", [#<Post id: 1, title: "Ruby News", comments: "dsfdsfdsfdsfdsfds", category_id: 1, user_id: 1, created_at: "2013-07-26 07:10:25", updated_at: "2013-07-26 07:19:27", photo_file_name: "pf-7.jpg", photo_content_type: "image/jpeg", photo_file_size: 162495, photo_updated_at: "2013-07-26 07:19:26">]]
目前哈希,其中月/年是关键,然后我在数组中的所有帖子都正确吗?
So at the moment i have a hash where the month/year is the key and then all my posts in an array, is that correct?
我要显示的是月/年,然后点击该月即可进入该月的所有帖子
All i want to display is the Month/Year and then click that month to be taken to all the posts for that month
感谢任何帮助
编辑
好吧,我,忘记了键/值配对的基础知识,我只有要显示的日期
ok silly me, forgot my basics on key/value pairing, i have got just the date to display
<% @posts_by_month.each do |m,p| %>
<%= link_to m %>
<% end %>
现在,我只需要单击链接即可查看该月的所有帖子
Now i just need to be able to click the link to see all posts for that month
推荐答案
您可以
= link_to m, posts_path(:month => m)
现在在个帖子中#index
,根据 params [:month]
if params[:month]
date = Date.parse("1 #{params[:month]}") # to get the first day of the month
@posts = Post.where(:created_at => date..date.end_of_month) # get posts for the month
else
@posts = Post.all
end
这篇关于按月/年红宝石显示帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!