Rails routes with date

允我心安 提交于 2020-01-15 18:50:31

问题


My question it's about use a filter by date in the route of a rails application, at the moment I all ready have the rule that match the pattern of the date in the routes.rb file, it's looks like this:

match "itineraries/:day/:month/:year" => "itineraries#index", 
        :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }
match "itineraries/new/:day/:month/:year" => "itineraries#new", 
        :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ }

resources :itineraries
match '/:controller(/:action(/:id))'
root :to => "itineraries#index"

That match for example /itineraries/01/01/2011, the problem comes when I generate a route from the resource, for example, itineraries_path(:year=>2011,:month=>1,:day=>1) generate:

/itineraries?day=1&month=1&year2011

instead of

/itineraries/01/01/2011

Is there a way to put the match rule inside the resource mapping?


回答1:


well, short answer is your route does exists, but it's not named yet (check rake routes to convince yourself) and that's why you can't call it just like that (using itineraries_path)

so, the correct way to do it would be for example:

match "itineraries/:day/:month/:year" => "itineraries#index", 
    :constraints => { :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ },
    :as => "itineraries_date"

(notice the :as part)

now, if you call itineraries_date_path(11,12,1998) it will give you itineraries/11/12/1998



来源:https://stackoverflow.com/questions/6317783/rails-routes-with-date

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