/websites/asd.com /websites/asd.com/dns_records/new
在我的config / routes.rb中,我有:@H_301_5@
map.resources :websites,:has_many => :dns_records map.resources :dns_records,:belongs_to => :website
然后我可以访问以下资源:@H_301_5@
/websites/1 /websites/1/dns_records
通过修改我的网站模型,我可以生成更好的URL,如下所示:@H_301_5@
class Website < ActiveRecord::Base def to_param domain_name end ... end # app/views/websites/index.erb <% @websites.each do |w| %> <%= link_to "Show #{w}",website_path(w) %> <% end %> # Produces a link to: /websites/example_without_periods_in_name
但是,对于包含“.”的域名.人物,Rails变得不开心.我相信这是因为’.’ character在ActionController :: Routing :: SEPARATORS中定义,它列出了用于拆分URL的特殊字符.这允许你做像/websites/1.xml这样的东西.@H_301_5@
那么,是否有一种干净的方式允许’.’ RESTful URL中的字符?@H_301_5@
我已经尝试重新定义ActionController :: Routing :: SEPARATORS以不包含’.’,这是解决问题的一种非常糟糕的方法.这会通过在其中附加“.:format”来混淆生成的URL.@H_301_5@
我也知道我可以添加:requirements => {:id => regexp}到我的config / routes.rb以匹配包含’.’的域名. (没有这个,params [:id]被设置为第一个’.’之前的域名部分),但这无助于RESTful生成URL /路径.@H_301_5@
非常感谢 :)
缺口@H_301_5@
解决方法
我需要添加:requirements => {:website_id => regexp}用于每个嵌套路由,它也包含一个带有句点的域名.@H_301_5@
这是我的工作路线:@H_301_5@
map.resources :websites,:requirements => { :id => /[a-zA-Z0-9\-\.]+/ } do |websites| websites.with_options :requirements => { :website_id => /[a-zA-Z0-9\-\.]+/ } do |websites_requirements| websites_requirements.resources :dns_records end end <%= link_to 'New DNS Record',new_website_dns_record_path(@website) %> # Produces the URL /websites/asd.com/dns_records/new
打电话给@H_301_5@
websites.with_options
只是与DRY保持一致,因此:不必为网站的所有嵌套路由指定要求.所以我也可以@H_301_5@
websites_requirements.resources :accounts websites_requirements.resources :monthly_bandwidth_records etc.