2011-06-07 45 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