为什么我的Rails 2路由有查询字符串?

时间:2010-09-01 15:51:39

标签: ruby-on-rails configuration routing query-string

我有时需要通过URL将其他参数传递给页面。我之前在路由文件中使用了几个通用占位符,我将其称为“genus”和“species”。这曾经有用,但现在它已开始使用查询字符串生成URL。

Rails版本是2.3.8。

路线文件是:

ActionController::Routing::Routes.draw do |map|
  map.root :controller => 'main', :action => 'index'
  map.connect ':controller', :action => 'index'
  map.connect ':controller/:action'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action/:genus/:id'
  map.connect ':controller/:action/:genus/:species/:id'
end

索引页面是:

<p>
<%= url_for :controller => 'main', :action => 'test', :genus => 42, :id => 1 %>
</p>

测试页面是

<p>
<%= params.inspect -%>
</p>

索引页面显示 / main / test?genus = 42&amp; id = 1 我希望 / main / test / 42/1

但是,如果我转到 / main / test / 42/1 ,我会看到正确的参数:

  

{“controller”=&gt;“main”,“action”=&gt;“test”,“genus”=&gt;“42”,“id”=&gt;“1”}

任何想法我做错了什么?

2 个答案:

答案 0 :(得分:5)

您的路线是颠倒的;您首先需要更具体的路由,以后需要更多通用路由。 Rails将采用它可用于匹配给定参数集的第一条路径。

ActionController::Routing::Routes.draw do |map|
  map.connect ':controller/:action/:genus/:species/:id'
  map.connect ':controller/:action/:genus/:id'
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action'
  map.connect ':controller', :action => 'index'
  map.root :controller => 'main', :action => 'index'
end

也就是说,你可以很容易地使用命名路由。

ActionController::Routing::Routes.draw do |map|
  map.with_options(:path_prefix => ":controller/:action") do |con|
    con.species ":genus/:species/:id"
    con.genus   ":genus/:id"
    con.connect ":id"
    con.connect ""
  end   
end

它可以为您提供以下路线:

species /:controller/:action/:genus/:species/:id
  genus /:controller/:action/:genus/:id
        /:controller/:action/:id
        /:controller/:action

然后,您可以使用:

<%=genus_path("main", "test", 42, 1) %>

获得:

"/main/test/42/1"

答案 1 :(得分:1)

这是一个相当愚蠢的解决方案,但这应该有效:

ActionController::Routing::Routes.draw do |map|
  map.connect ':controller/:action/:genus/:species/:id', :genus => /\d+/,
    :species => /\d+/, :id => /\d+/
  map.connect ':controller/:action/:genus/:id', :genus => /\d+/, :id => /\d+/
  map.connect ':controller/:action/:id'
  map.connect ':controller/:action'
  map.connect ':controller', :action => 'index'
  map.root :controller => 'main', :action => 'index'
end

问题是路由的所有组件在Rails 2中都是可选的。幸运的是,这在Rails 3中更好。我的猜测与路由的优先级有关,已经在版本2.3.5-2.3周围发生了变化。 8。