不同的路线,但对Rails中的模型子类使用相同的控制器 [英] Different routes but using the same controller for model subclasses in Rails
问题描述
我有一个Model属性,其中包含使用STI的子类,
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
工作正常,但我不确定如何识别控制器内的子类以呈现正确的看法。就是/ restaurants工作并转到属性控制器,但是我不能说他们想要Restaurant子类吗?
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.
更新:或者,您也可以在 routes.rb
中尝试类似的操作:
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}
然后,您可以使用before过滤器检查params [:what]并相应地更改行为
Then you can use a before filter to check params[:what] and change behaviour accordingly.
示例:
class PropertiesController < ApplicationController
before_filter select_model
def select_model
@model = params[:what].constantize
end
def show
@model.find(params[:id])
...
end
...
end
这篇关于不同的路线,但对Rails中的模型子类使用相同的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!