2011-06-07 31 views
1

我试图为我的博客存档创建一个侧栏,列出我的博客条目的所有月份,因此当您点击链接(如“2007年6月”)时,将加载从2007年6月起的所有博客。 继承人我的link_to在Rails3中检索记录的created_by字段以传递给月份和年份?

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %> 

month.first是我拉了一项纪录。应我的控制器是这个样子?:

@blog_posts = BlogPost.where(:created_at.strftime("%Y-%m-%d") => params[:date]).(:select => "title, id, slug, created_at", :order => "created_at DESC") 

我希望我可以记录CREATED_BY字段转换到我可以传递一个匹配的格式,但我得到一个未定义的方法埃罗

回答

0

基本上我同意丹呱 - 呱是说( +1)。他的回答中唯一的错误是.to_date如果在params[:date]中没有完整的日期字符串(如他的示例中),则会引发错误。所以我的建议是:

查看:

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %> 

控制器:

@blog_posts = BlogPost. 
    where(:created_at => params[:date].to_date.beginning_of_month..params[:date].to_date.end_of_month). 
    order("created_at desc") 

与你原来的代码的问题是,你试图调用strftime:created_at,这是不可能的。

或者,如果你不喜欢你的URL完整的日期,你可以这样做:

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m")) %> 

和:

@blog_posts = BlogPost. 
    where(:created_at => "#{params[:date]}-01".to_date.beginning_of_month.."#{params[:date]}-01".to_date.end_of_month). 
    order("created_at desc") 
+0

哦,真棒,是的,它做到了。多谢你们! – rugbert 2011-06-07 17:46:56

3

这个怎么样?

带上链接到只有年月:

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(:date => month.first.strftime("%Y-%m")) %> 

然后,使用范围语法来获得之间的SQL:

@blog_posts = BlogPost. 
       where(:created_at => (params[:date].to_date..(params[:date].to_date + 1.month))). 
       order("created_at desc") 
+0

卫生署啊,我的意思只是传递年月(mustve副本pasta'd)位我得到德.to_date – rugbert 2011-06-07 03:56:51

+0

一个未定义的方法怎么样,如果你编辑的路径是blog_archive_month_path(:日期=> month.first.strftime( “%Y-%M”)) – 2011-06-07 04:02:47

+0

@ rugbert - 'to_date'只在字符串包含完整日期时才有效:您还需要一天。除此之外,我建议使用'beginning_of_month'和'end_of_month'。例如:'2011-6-7'.to_date.beginning_of_month => Wed,01 June 2011'。 – Mischa 2011-06-07 04:20:13