简体   繁体   English

Rails:具有自定义路线的数据库记录…?

[英]Rails: Database records with custom route…?

I have a model, target, that holds a number of records that are timestamped. 我有一个模型,目标,其中保存了许多带有时间戳的记录。 On the corresponding controller, I list the months of those records by doing the following: 在相应的控制器上,我通过执行以下操作列出了这些记录的月份:

In models/target.rb models / target.rb中

def month
   self.recorded_on.strftime('%B')
end

In controllers/targets_controller.rb controllers / targets_controller.rb中

@records = Target.find :all

In views/targets/index.html.haml views / targets / index.html.haml中

%ul
  - @records.group_by(&:month).sort.each do |month, data|
    %li= link_to month, ''

That all works great for listing the available months for the records that I have. 所有这些都非常适合列出我拥有的记录的可用月份。 Next, I want to be able to click on the month and get a report of all the records for that month, at the following path generated with year and the month: /targets/2009/04 接下来,我希望能够单击月份,并在通过年份和月份生成的以下路径中获得该月份所有记录的报告: / targets / 2009/04

How would I do this? 我该怎么做?

Add some named scopes to your Target model to support finding by year and by month number. 将一些命名范围添加到Target模型,以支持按年份和月份编号查找。 Something like: 就像是:

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

(Note that the conditions here are using MySQL syntax.) (请注意,这里的条件使用的是MySQL语法。)

Assuming you're using RESTful routes, set up a named route like the one below in your config/routes.rb file (make sure it's declared before the default route): 假设您使用的是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 can use this route in your view like this: —您可以在视图中使用此路线,如下所示:

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

(Note that the leading zero for the month is optional because of the :requirements regular expression in the named route defined above) (请注意,由于前面定义的命名路由中的:requirements正则表达式,因此月份的前导零是可选的)

Finally, in your TargetsController , set up the index action to use the named_scopes defined earlier: 最后,在TargetsController ,将index操作设置为使用之前定义的named_scopes:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM