雖然它可能會更好,讓您的蛞蝓看上去像「1-學習軌道」,因爲Rails 3中現在allows the use of Rack applications處理路線,所以你可以做這樣的事情:
# lib/topic_slugger.rb
class TopicSlugger
AD_KEY = "action_dispatch.request.path_parameters"
def self.call(env)
controller = (env["PATH_INFO"].split("/")[1].camelize+"Controller").constantize
glob = env[AD_KEY][:glob]
slug, action_name = nil
if glob
path_params = glob.split("/")
if path_params.length == 1
if ["new","edit"].include?(path_params.first)
# no slug present
action_name = path_params.first
else
slug = path_params.first
end
else
action_name = path_params.first
slug = path_params.last
end
end
env[AD_KEY][:slug] = slug if slug
action = if action_name # "new" or "edit"
action_name.to_sym
else
case env["REQUEST_METHOD"]
when "PUT" then :update
when "DELETE" then :destroy
else :show
end
end
controller.action(action).call(env)
end
end
# config/routes.rb
require 'topic_slugger'
Ztest::Application.routes.draw do
# handle show, new, edit, update, destroy
match 'topics/:id/*glob' => TopicSlugger
# handle index, create
resources :topics
end
這需要的請求表單"/topics/1/foo/bar"
並將它們傳遞給TopicSlugger Rack應用程序,該應用程序決定glob是否包含組合動作/ slug(如"new/learning-rails"
)或者只是一個slug("learning-rails"
),將slug添加到環境的請求參數中,然後將環境傳遞給控制器動作,它本身就是一個Rack應用程序。 「索引」和「創建」通常由resources
聲明處理。
因此,例如"GET /topics/1/new/learning-rails"
將被派往TopicsController#new
與{ :id => "1", :slug => "learning-rails, :glob => "new/learning-rails" }
URL存根params散列,更通常被稱爲在Rails社區的URL蛞蝓。不要試圖迂腐,只是想法它可以幫助人們回答你的問題,正確地理解你的問題。 – 2011-02-11 05:14:23