Rails Routing: what is the difference between :conditions and :requirements in routing?
When should I use :conditions or :requirements in rails routing?
Here are two examples:
:conditions
map.connect "/foo/:view/:permalink", :controller => "foo",
:action => "show", :view => /plain|fancy/,
:permalink => /[-a-z0-9]+/,
:conditio开发者_如何学Pythonns => { :method => :get }
end
:requirements
map.connect 'posts/index/:page',
:controller => 'posts',
:action => 'index',
:requirements => {:page => /\d+/ },
:page => nil
end
The only option :conditions
takes is :method
(i.e. :get
, :post
, etc.), letting you restrict which methods may be used to access the route:
map.connect 'post/:id', :controller => 'posts', :action => 'show', :conditions => { :method => :get }
:requirements
, on the other hand, lets you specify a regular expression that the parameter must match, e.g. if the parameter is a postal code you can give it a regular expression that only matches postal codes:
map.geocode 'geocode/:postalcode', :controller => 'geocode', :action => 'show', :requirements => { :postalcode => /\d{5}(-\d{4})?/ }
(You can even drop :requirements
and use this shorter form:)
map.geocode 'geocode/:postalcode', :controller => 'geocode', :action => 'show', :postalcode => /\d{5}(-\d{4})?/
Look under "Route conditions" and "Regular Expressions and parameters" in ActionController::Routing, from which I stole the above examples.
精彩评论