Rails 中的模型子类使用不同的路线但使用相同的控制器

发布于 2024-08-22 00:07:57 字数 359 浏览 5 评论 0原文

我有一个模型属性,它具有使用 STI 的子类,

并且我希望所有人都使用相同的控制器,并且根据子类仅具有不同的视图部分。

Property
Restaurant < Property
Landmark < Property

它可以找到,但我不确定如何辨别控制器内的子类以呈现正确的视图。 IE。 /restaurants 工作并转到属性控制器,但我不知道他们想要 Restaurant 子类?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅浅 2024-08-29 00:07:57

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

class RestaurantsController < PropertiesController
end

在路由中,您将餐厅映射到餐厅控制器。

更新: 或者,您可以在 routes.rb 中尝试类似的操作:

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

然后您可以使用 before 过滤器来检查 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文