【问题标题】:Different routes but using the same controller for model subclasses in Rails不同的路线,但在 Rails 中对模型子类使用相同的控制器
【发布时间】:2010-02-16 23:50:23
【问题描述】:

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

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

Property
Restaurant < Property
Landmark < Property

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

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

【问题讨论】:

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


    【解决方案1】:

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

    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
    

    【讨论】:

    • 是的,但我想让它们使用相同的控制器,只是视图部分略有不同。
    • @holden:我添加了另一个可能对您有用的解决方案
    • 我尝试了完全相同的事情,虽然我使用了 :subclass 而不是 :what 但它似乎不起作用。 params[:what] 是 nil,我从 params 得到的只是来自 /restaurants 的“actionindexcontrollerproperties”;-(
    • 你是对的。我以前没有注意到这一点。我以前没有在宁静的路线上使用过它。我认为添加第二个控制器并没有真正的问题,因为它不会复制任何代码,它只是一个包含两行的附加文件。
    • 嗯,在我的情况下,它将是许多不同的文件。我只是列出了一个子模型,但实际上可能会有 5-6 个。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    相关资源
    最近更新 更多