Rails routes with dates

≯℡__Kan透↙ 提交于 2019-12-04 08:37:07

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!