【问题标题】:Passing variables to Controller via RESTful routing in Rails在 Rails 中通过 RESTful 路由将变量传递给控制器
【发布时间】: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


    【解决方案1】:

    由于没有回复并且我找到了解决方案,我将自己回答这个问题。如果您还有一种情况,您可能有一个模型或一个表,其中包含多个条目,但对于其中一些条目,您可能需要单独的视图,这可能会对您有所帮助。

    您很可能希望拥有不同的索引,为此只需使用 collection get:

     map.resources :episodes, :collection => {:simpsons=> :get, :flintstones=> :get} do |episode|
     ....and so on
    

    只需在控制器中添加名为“simpsons”和“flintstones”的方法。而且,对于编辑、查看和删除方法,如果需要,您可以通过确定手头条目的 ID 来使用一些额外的逻辑。类似@episode = Episode.find(params[:id]),如果@episode.criteria == ...something... 然后渲染这个或另一个视图。

    【讨论】:

      猜你喜欢
      • 2015-01-06
      • 2017-08-09
      • 2015-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多