简体   繁体   中英

Passing variables to Controller via RESTful routing in Rails

The following question is related to passing a variable from routes to the controller. I have a Ruby on Rails (v 2.3.3) app with one model, which is delivered to the user with multiple views. The current solution involves using multiple controllers which are triggered by multiple routes. For example:

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

However, for the sake of DRYness I would like these routes to operate with the same controller. In order for the controller to distinct between the routes I would like to pass along a variable via the route. For example:

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

So in the controller I could do this:

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

I found a way to do this with non-RESTful routing (map.with_options etc.), but I'd prefer to use RESTful routes with map.resource(s). One ugly solution might be to parse the request URI in the controller, which I'd not prefer.

Since there are no replies and I found a solution, I am going to answer this question myself. If you also have a situation, where you might have a model or a table, which has multiple entries, but for some of them you might need separate views, this might benefit you a bit.

Most likely you would like to have different indexes and for that simply use collection get:

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

Simply add the methods named "simpsons" and "flintstones" in your controller. And, for the edit, view and delete methods you can use a bit of extra logic, if necessary, by determening the ID of the entry at hand. Something like @episode = Episode.find(params[:id]), if @episode.criteria == ...something... then render this or the other view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM