不同的路由,但在Rails中使用相同的控制器进行模型子类

时间:2010-02-16 23:50:24

标签: ruby-on-rails routing routes subclass single-table-inheritance

我有一个Model属性,它有使用STI的子类,

我希望所有人都使用相同的控制器,只有不同的视图部分取决于子类。

Property
Restaurant < Property
Landmark < Property

它工作查找除了我不知道如何识别控制器内的子类以呈现正确的视图。 IE浏览器。 /餐馆工作,并去物业控制器,但我不能告诉他们他们想要餐厅的子类?

map.resources :restaurant, :controller => :properties
map.resources :properties

1 个答案:

答案 0 :(得分:5)

解决问题的一个简单方法是创建一个子控制器:

class RestaurantsController < PropertiesController
end

在路线中,您可以将餐馆映射到餐馆控制器。

更新:或者您可以在routes.rb中尝试类似的内容:

map.resources :restaurants, :controller => :properties, :requirements => {:what => :Restaurant}
map.resources :properties, :requirements => {:what => :Property}

然后你可以使用前置过滤器来检查params [:what]并相应地改变行为。

示例:

class PropertiesController < ApplicationController
  before_filter select_model

  def select_model
    @model = params[:what].constantize
  end

  def show
    @model.find(params[:id])
    ...
  end

  ...
end