【问题标题】:Rails Routing: what is the difference between :conditions and :requirements in routing?Rails 路由:路由中的 :conditions 和 :requirements 有什么区别?
【发布时间】:2009-12-07 19:40:48
【问题描述】:

什么时候应该在 rails 路由中使用 :conditions 或 :requirements?

这里有两个例子:

:条件

map.connect "/foo/:view/:permalink", :controller => "foo",
    :action => "show", :view => /plain|fancy/,
    :permalink => /[-a-z0-9]+/,
    :conditions => { :method => :get }
end

:要求

 map.connect 'posts/index/:page',
            :controller => 'posts',
            :action => 'index',
            :requirements => {:page => /\d+/ },
            :page => nil
 end

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:

    :conditions 采用的唯一选项是:method(即:get:post 等),可让您限制可用于访问路由的方法:

    map.connect 'post/:id', :controller => 'posts', :action => 'show',
                :conditions => { :method => :get }
    

    :requirements,另一方面,允许您指定参数必须匹配的正则表达式,例如如果参数是邮政编码,你可以给它一个只匹配邮政编码的正则表达式:

    map.geocode 'geocode/:postalcode', :controller => 'geocode',
                :action => 'show', :requirements => { :postalcode => /\d{5}(-\d{4})?/ }
    

    (您甚至可以删除 :requirements 并使用这个更短的形式:)

    map.geocode 'geocode/:postalcode', :controller => 'geocode',
                :action => 'show', :postalcode => /\d{5}(-\d{4})?/
    

    查看ActionController::Routing中的“路由条件”和“正则表达式和参数”,我从中窃取了上面的示例。

    【讨论】:

      猜你喜欢
      • 2019-09-24
      • 2020-11-06
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 2019-04-16
      • 2016-07-17
      • 2014-06-29
      相关资源
      最近更新 更多