5

因此,我有一个每周日历视图,并且设置了一条路线以接受 /:year/:month/:day 作为开始日期。

  match "events/(:year/:month/:day)" => "events#index", 
      :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ },
      :as => "events_date"

关于这条路线的使用,我有两个问题。首先,在解析参数时,这就是我正在做的事情:

unless params[:year].nil? || params[:month].nil? || params[:day].nil?
  start_date = Date.new(params[:year].to_i, params[:month].to_i, params[:day].to_i)
end
start_date = start_date.nil? ? Date.today : start_date

这让我觉得非常冗长和丑陋。有没有更好的办法?

当链接到日历中的另一周时(每周翻页),我是否必须做类似的事情

#assume an date object with the desired start date
link_to events_date_path(date.strftime('%Y'), date.strftime('%m'), date.strftime('%d'))

这似乎也有点冗长和丑陋。在路线中处理日期的最佳方式是什么?

4

1 回答 1

8

My suggestion would be to not use three separate variables. That way you don't end up with a lot of extra null checking and sanity checking in your controller. You could turn your match in to something look like this, with your constraints still in tact:

match "events/(:date)" => "events#index", 
      :constraints => { :date => /\d{4}-\d{2}-\d{2}/ },
      :as => "events_date"

Thus you would end up with something a little more sane in the controller:

unless params[:date]
  start_date = params[:date].strftime("%Y-%m-%d').to_date # assuming you want a Date
end

And I usually do those types of 'if this is set' checks something more like this, because I find it a bit more readable:

start_date = Date.today unless defined? start_date

You could even roll those last two together:

start_date = defined?(params[:date]) ? params[:date].strftime("%Y-%m-%d').to_date : Date.today
于 2012-05-02T20:57:40.430 回答