【发布时间】:2010-03-07 13:54:40
【问题描述】:
以下问题与将变量从路由传递到控制器有关。我有一个带有一个模型的 Ruby on Rails (v 2.3.3) 应用程序,它通过多个视图交付给用户。当前的解决方案涉及使用由多个路由触发的多个控制器。例如:
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 等)执行此操作的方法,但我更喜欢将 RESTful 路由与 map.resource(s) 一起使用。一种丑陋的解决方案可能是在控制器中解析请求 URI,我不喜欢这样做。
【问题讨论】:
标签: ruby-on-rails variables controller rest