我有一个模型,目标,有很多记录是有时间戳的。在相应的控制器上,我通过以下操作列出这些记录的月份:
在models/target.rb中
def month
self.recorded_on.strftime('%B')
end在controllers/targets_controller.rb中
@records = Target.find :all在views/targets/index.html.haml中
%ul
- @records.group_by(&:month).sort.each do |month, data|
%li= link_to month, ''这对于列出我所拥有的记录的可用月份都很有用。接下来,我希望能够单击月份,并在用年份和月份生成的以下路径中获取该月份所有记录的报告:/targets/2009/04
我该怎么做?
发布于 2009-04-24 18:28:19
将一些命名范围添加到您的Target模型中,以支持按年和按月份进行查找。类似于:
class Target < ActiveRecord::Base
named_scope :by_month,
lambda { |month| { :conditions => ['MONTH(recorded_on) = ?',
month] }}
named_scope :by_year,
lambda { |year| { :conditions => ['YEAR(recorded_on) = ?', year] }}
.
.
.
end(请注意这里的条件使用的是MySQL语法。)
假设您使用的是RESTful路由,那么在您的config/routes.rb文件中设置一个命名路由 (确保它在默认路由之前声明):
map.targets_by_month '/targets/:year/:month', :controller => 'targets',
:requirements => { :year => /\d{4}/, :month => /\d{1,2}/ },
:conditions => { :method => :get }-You可以在视图中使用此路由,如下所示:
<%= link_to 'Show April 2009 Targets', targets_by_month_path('2009', '04') %>(注意,这个月的前导零是可选的,因为上面定义的命名路由中有:requirements正则表达式)
最后,在您的TargetsController中,设置index操作以使用前面定义的named_scopes:
def index
@records = Target.by_year(params[:year]).by_month(params[:month])
.
.
.
endhttps://stackoverflow.com/questions/786948
复制相似问题