定义常规路由中的默认值

时间:2010-02-15 19:01:24

标签: ruby-on-rails routing

我在routes.rb文件中添加了这一行

map.connect ':controller/:action/:id/:title', :controller => "recipes"

认为我在URL的末尾添加了配方标题,这只适用于配方控制器。我还在文件的开头声明了一个像这样的资源

map.resources :recipes

以下网址完美无缺

http://localhost:3000/recipes/show/84/testing201
http://localhost:3000/recipes/edit/84/testing2010

然而,当我说rake路线时,我得到以下配方控制器

recipes GET    /recipes(.:format)                 {:controller=>"recipes", :action=>"index"}
             POST   /recipes(.:format)                 {:controller=>"recipes", :action=>"create"}
  new_recipe GET    /recipes/new(.:format)             {:controller=>"recipes", :action=>"new"}
 edit_recipe GET    /recipes/:id/edit(.:format)        {:controller=>"recipes", :action=>"edit"}
      recipe GET    /recipes/:id(.:format)             {:controller=>"recipes", :action=>"show"}
             PUT    /recipes/:id(.:format)             {:controller=>"recipes", :action=>"update"}
             DELETE /recipes/:id(.:format)             {:controller=>"recipes", :action=>"destroy"}

在底部我看到了这个

/:controller/:action/:id/:title    
/:controller/:action/:id           
/:controller/:action/:id(.:format) 

从输出看起来似乎标题不适用于配方路线,但它在全球范围内应用。我该如何解决这个问题,所以通配符(“/:controller /:action /:id /:title”中的“:title”)只适用于食谱?

2 个答案:

答案 0 :(得分:0)

您正在混合两种不同的路由概念。一个是RESTful路线(在谷歌上阅读它),另一个是通用/一般路线。你应该只使用其中一个。建议使用RESTful(map.resources :recipes)。但首先你需要决定使用哪一个。

另外这个定义是错误的:

map.connect ':controller/:action/:id/:title', :controller => "recipes"

你有:路由中的控制器变量,然后你说:控制器应该绑定到'食谱'。解决这个问题的一种方法是:

map.connect '/recipes/:action/:id', :controller => "recipes"

或更好

map.connect '/recipes/:id/:action', :controller => "recipes"

你正在接近RESTful路线。

如果您想要路线中的标题,那么请使用带有RESTful资源的命名路线。但请勿在一条路线中混用:id:title。只使用一个参数(或两者合并但这是另一个故事)。

map.resources :recipes, :except => [:show]
map.recipe '/recipe/:title', :controller => 'recipes', :action => 'show'

您可能需要覆盖to_param模型中的Recipe方法:

def Recipe < ActiveRecord::Base
  def to_param
     title
  end
end

答案 1 :(得分:0)

我会评论map.resources,评论连接并再次使用map.with_options:

map.with_options :controller => 'recipes' do |recipes|
 recipes.list '', :action => 'index'
 recipes.delete '/delete/:id/:title', :action => 'delete'
 recipes.edit '/edit/:id/:title', :action => 'edit'
end
相关问题