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
holden
  • 13,471
  • 22
  • 98
  • 160

1 Answers1

5

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
EmFi
  • 23,435
  • 3
  • 57
  • 68
Tomas Markauskas
  • 11,496
  • 2
  • 33
  • 35
  • yes, but i'd like to keep them using the same controller, with only slightly different view partials. – holden Feb 16 '10 at 23:55
  • @holden: I've added another solution which might work for you – Tomas Markauskas Feb 17 '10 at 00:02
  • 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 Feb 17 '10 at 00:09
  • 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 Feb 17 '10 at 00:18
  • 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 Feb 17 '10 at 00:34
  • 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 Feb 17 '10 at 00:51