Ruby 检索记录';在Rails3中,是否按字段创建了年和月?

Ruby 检索记录';在Rails3中,是否按字段创建了年和月?,ruby,ruby-on-rails-3,actioncontroller,Ruby,Ruby On Rails 3,Actioncontroller,我试图为我的博客档案制作一个侧栏,列出我的博客条目的所有月份,这样当你点击“2007年6月”之类的链接时,从2007年6月开始的所有博客都会被加载。 这是我的链接 <%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %> 我希望我可以将字段创建的记录转换为可以在匹配中传递的格式,但是我得到了一个未定义的方法erro这个怎么样 将链接降

我试图为我的博客档案制作一个侧栏,列出我的博客条目的所有月份,这样当你点击“2007年6月”之类的链接时,从2007年6月开始的所有博客都会被加载。 这是我的链接

<%= link_to month.first.strftime("%B %Y"), blog_archive_month_path(month.first.strftime("%Y-%m-%d")) %>
我希望我可以将字段创建的记录转换为可以在匹配中传递的格式,但是我得到了一个未定义的方法erro

这个怎么样

将链接降低到仅一年一个月:

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

基本上我同意丹·克罗克的说法(+1)。他的回答中唯一的错误是,如果
参数[:date]
中没有完整的日期字符串,则
.to_date
会抛出错误(如他的示例中所示)。因此,我的建议是:

视图:

原始代码的问题是,您试图在
:created_上调用
strftime
,这是不可能的

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

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

是的,我只是想通过年-月(必须复制意大利面)位我得到了一个未定义的方法。to_date如果你将路径编辑为blog_archive_month_path(:date=>month.first.strftime(%Y-%m))@rugbert-
to_date
只在字符串包含完整日期时有效:你还需要日期。除此之外,我建议使用
月初
月底
。例如:
“2011-6-7”。到2011年6月1日星期三,月初=>如果我理解正确,我的控制器应该是这样的:`@blog\u posts=BlogPost.where(:created\u by.to\u date.start\u of\u month=>参数[:date])(:select=>“title,id,slug,created\u at”“,:order=>“created\u at DESC”)“好吧,问题是我不能运行:created_by字段中的任何方法controller@rugbert-不,我不是这个意思。我将自己添加一个答案,因为很难在注释中显示代码。哦,太棒了,是的,这样做了。谢谢大家!
@blog_posts = BlogPost.
              where(:created_at => (params[:date].to_date..(params[:date].to_date + 1.month))).
              order("created_at desc")
<%= 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")
<%= 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")