本文介绍了Rails路线与日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个每周的日历视图,我有一条路线设置接受/:年/月/日的开始日期。

So I have a weekly calendar view and I have a route set up to accept /:year/:month/:day for the start date.

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

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

I have two questions regarding the use of this route. First, when parsing the params, this is what I'm doing:

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

这使我感到非常冗长和丑陋。有没有更好的方法?

This strikes me as pretty verbose and kind of ugly. Is there a better way?

当链接到日历中的另一个星期(寻呼周到周)时,我必须做一些像

And when making a link to another week in the calendar (for paging week to week), do I have to do something like

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

哪个也似乎一种冗长和丑陋。在路线中使用日期的最佳方式是什么?

Which also seems kind of verbose and ugly. What's the best way to work with dates in routes?

推荐答案

我的建议是不要使用三个单独的变量。这样你就不会在你的控制器中得到很多额外的空值检查和理智检查。你可以把你的比赛变成这样的东西,你的限制还是有点尴尬:

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

这篇关于Rails路线与日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 19:04
查看更多