gpt4 book ai didi

ruby-on-rails - Rails 路由 : what is the difference between :conditions and :requirements in routing?

转载 作者:行者123 更新时间:2023-12-01 08:41:38 26 4
gpt4 key购买 nike

什么时候应该在 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

最佳答案

: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 中的“路由条件”和“正则表达式和参数” ,我从中偷了上面的例子。

关于ruby-on-rails - Rails 路由 : what is the difference between :conditions and :requirements in routing?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1862392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com