Rails:带有自定义路由的数据库记录......?

时间:2009-04-24 17:59:53

标签: ruby-on-rails routes

我有一个模型,目标,它包含许多带时间戳的记录。在相应的控制器上,我通过执行以下操作列出这些记录的月份:

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

我该怎么做?

1 个答案:

答案 0 :(得分:2)

Target模型添加一些named scopes,以支持按年份和月份编号查找。类似的东西:

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文件中设置named route,如下所示(确保在默认路由之前声明):

map.targets_by_month '/targets/:year/:month', :controller => 'targets',
                :requirements => { :year => /\d{4}/, :month => /\d{1,2}/ },
                :conditions => { :method => :get }

- 您可以在视图中使用此路线,如下所示:

<%= link_to 'Show April 2009 Targets', targets_by_month_path('2009', '04') %>

(请注意,由于上面定义的命名路由中的:requirements正则表达式,月份的前导零是可选的。

最后,在TargetsController中,设置index操作以使用之前定义的named_scope:

def index
  @records = Target.by_year(params[:year]).by_month(params[:month])
  .
  .
  .
end