按日期在Rails中对博客post进行分组和排序

我在网上搜索过,但没有找到答案。 我正在尝试根据日期为我的博客提供一个非常标准的存档选项。 url blog.com/archive/2009的请求显示了2009年的所有post,blog.com/archive/2009/11显示了2009年11月的所有post等。我发现了两个不同的代码,但对我没什么帮助。

def display_by_date year = params[:year] month = params[:month] day = params[:day] day = '0'+day if day && day.size == 1 @day = day if (year && month && day) render(:template => "blog/#{year}/#{month}/#{date}") elsif year render(:template => "blog/#{year}/list") end end def archive year = params[:year] month = params[:month] day = params[:day] day = '0'+day if day && day.size == 1 if (year && month && day) @posts_by_month = Blog.find(:all, :conditions => ["year is?", year]) else @posts_by_month = Blog.find(:all).group_by { |post| post.created_at.strftime("%B") } end end 

任何帮助表示赞赏。

编辑:我设法让它工作。 如果你去’blog / 2010’,你会看到2010年发布的所有post,如果你去’blog / 2010 / apr’,你会看到2010年4月发布的所有post等。

 def archive year = params[:year] month = params[:month] day = params[:day] if (year && month && day) requested_date = Date.new(year.to_i, Date.parse(month).month.to_i, day.to_i) from = requested_date - 1 to = requested_date + 1 @posts_by_month = Blog.find(:all, :conditions => ["due BETWEEN ? AND ?", from, to]) elsif (year && month) requested_month = Date.new(year.to_i, Date.parse(month).month.to_i) end_month = requested_month.end_of_month @posts_by_month = Blog.find(:all, :conditions => ["due BETWEEN ? AND ?", requested_month, end_month]) else requested_year = Date.new(year.to_i) @posts_by_month = Blog.find(:all, :conditions => ["created_at BETWEEN ? AND ?", requested_year, requested_year.end_of_year ]) end end #routes.rb map.connect 'blog/:year/:month/:day', :controller => 'blogs', :action => 'archive', :year => /\d{4}/, :month => /\w{3}/, :day => /\d{2}/, :day => nil, :month => nil 

我不知道这是否是“好”的代码,但我相信有人可以做得更好。 如果有人这样做,我会很感激。

我更新了发送-hil对Rails 4的回答。和他一样,我不知道这是否是“好”的代码,但它似乎对我有用。 如果我发现/做出任何改进,我会更新这篇文章。

  def archive year = params[:year] month = params[:month] day = params[:day] if (year && month && day) requested_date = Date.new(year.to_i, Date.parse(month).month.to_i, day.to_i) from = requested_date - 1 to = requested_date + 1 @posts = Post.find_by_sql([ "SELECT * FROM posts WHERE created_at BETWEEN ? AND ?", from, to]) elsif (year && month) requested_month = Date.new(year.to_i, Date.parse(month).month.to_i) end_month = requested_month.end_of_month @posts = Post.find_by_sql([ "SELECT * FROM posts WHERE created_at BETWEEN ? AND ?", requested_month, end_month ]) else requested_year = Date.new(year.to_i) @posts = Post.find_by_sql([ "SELECT * FROM posts WHERE created_at BETWEEN ? AND ?", requested_year, requested_year.end_of_year ]) end end #routes.rb match ':controller/:action/:year/(:month)/(:day)', via: [:get], :controller => "posts", :action => "archive", :year => /\d{4}/, :month => /\w+/, :day => /\d{2}/ 

而不是博客我使用“post”和路径的forms是www.site.com/posts/archive/2015/September/20