我在网上搜索过,但没有找到答案。我正在尝试根据日期为我的博客提供一个非常标准的存档选项。 url blog.com/archive/2009的请求显示了2009年的所有帖子,blog.com/archive/2009/11显示了2009年11月的所有帖子等。我发现了两个不同的代码但对我没有太大帮助。
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
感谢任何帮助。
答案 0 :(得分:0)
编辑:我设法让它发挥作用。如果你去'blog / 2010',你会看到2010年发布的所有帖子,如果你去'blog / 2010 / apr',你会看到2010年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_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
我不知道这是否是“好”代码,但我确信有人可以做得更好。如果有人这样做,我会很感激。