以下問題與將路由變量傳遞給控制器有關。我有一個模型的Ruby on Rails(v 2.3.3)應用程序,該模型通過多個視圖交付給用戶。目前的解決方案涉及使用由多條路線觸發的多個控制器。例如:在Rails中通過RESTful路由將變量傳遞給控制器
ActionController::Routing::Routes.draw do |map| # defines map
map.resource :simpsons, :only => [] do |b|
b.resources :episodes, :controller => "SimpsonsEpisodes"
end
map.resource :flintstones, :only => [] do |b|
b.resources :episodes, :controller => "FlintstonesEpisodes"
end
但是,爲了乾燥,我希望這些路線使用相同的控制器。爲了讓控制器區分不同的路線,我想通過路線傳遞一個變量。例如:
map.resource :simpsons, :only => [] do |b|
b.resources :episodes, :controller => "Episodes", :type => "simpsons"
end
map.resource :flintstones, :only => [] do |b|
b.resources :episodes, :controller => "Episodes", :type => "flintstones"
end
所以在控制器我可以這樣做:
case(type)
when "simpsons" then ... do something for the Simpsons ...
when "flintstones" then ... do something for the Simpsons ...
else .... do something for all episodes ....
end
我找到了一種與非RESTful路由(map.with_options等),要做到這一點,但我寧願使用map.resource(s)使用RESTful路由。一個醜陋的解決方案可能是解析控制器中的請求URI,這是我不喜歡的。