以下问题与将路由变量传递给控制器有关。我有一个模型的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,这是我不喜欢的。