问题
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") }
In my view i then render like so
<% @posts_by_month.each do |m| %>
<%= m %>
<% end %>
Which returns this in the view
["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
Any help appreciated
EDIT
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
回答1:
You could do
= link_to m, posts_path(:month => m)
Now in posts#index, fetch the posts based on 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
来源:https://stackoverflow.com/questions/18010721/display-posts-by-month-year-ruby