Different routes but using the same controller for model subclasses in Rails
I have a Model Property which has subclasses using STI,
and which I would like all to use the same controller with only different view partials de开发者_高级运维pending on the subclass.
Property
Restaurant < Property
Landmark < Property
It works find except I'm not sure how to discern the subclass inside the controller to render the correct view. Ie. /restaurants works and goes to the properties controller but I can't tell that they want the Restaurant subclass?
map.resources :restaurant, :controller => :properties
map.resources :properties
A simple way to fi the problem would be to create a Sub-Controller:
class RestaurantsController < PropertiesController
end
In the routes you would map restaurants to the restaurants controller.
Update: Alternatively you could try something like this in your routes.rb
:
map.resources :restaurants, :controller => :properties, :requirements => {:what => :Restaurant}
map.resources :properties, :requirements => {:what => :Property}
Then you can use a before filter to check params[:what] and change behaviour accordingly.
Example:
class PropertiesController < ApplicationController
before_filter select_model
def select_model
@model = params[:what].constantize
end
def show
@model.find(params[:id])
...
end
...
end
精彩评论