[英]Defining defaults in regular routes
我在我的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
但是,當我說耙路徑時,配方控制器得到以下信息
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”)僅適用於配方?
您正在混合兩種不同的路由概念。 一種是RESTful路由(請在Google上閱讀),另一種是通用/通用路由。 您應該只使用其中之一。 推薦使用RESTful( map.resources :recipes
)。 但是首先,您需要確定要使用哪個。
再加上這個定義是錯誤的:
map.connect ':controller/:action/:id/:title', :controller => "recipes"
路由中有:controller變量,然后說:controller應該綁定到“配方”。 解決它的一種方法是:
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'
您可能需要在Recipe
模型中覆蓋to_param
方法:
def Recipe < ActiveRecord::Base
def to_param
title
end
end
我會評論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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.