Different routes but using the same controller for model subclasses in Rails

爷,独闯天下 提交于 2019-12-08 06:40:54

问题


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

回答1:


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


来源:https://stackoverflow.com/questions/2277299/different-routes-but-using-the-same-controller-for-model-subclasses-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!