views:

330

answers:

1

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 depending 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
+4  A: 

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
Tomas Markauskas
yes, but i'd like to keep them using the same controller, with only slightly different view partials.
holden
@holden: I've added another solution which might work for you
Tomas Markauskas
i tried the exact same thing, although I used :subclass instead of :what but it doesn't seem to work. params[:what] is nil and all i get form params is "actionindexcontrollerproperties" from /restaurants ;-(
holden
You're right. I haven't noticed this before. I haven't used this with restful routes before. I think adding a second controller is not really problematic as it's not duplicating any code, it's just one additional file with two lines in it.
Tomas Markauskas
Well, in my case it'll be many different files. I just listed one submodel, but in reality there will probably be 5-6.
holden
For resource(s) default options are passed as :requirements. I've updated the answer for you and provided an example filter to make things more DRY
EmFi
ah, the requirements option works beautifully, thank you!
holden