2014-01-21 22 views
0

假設我有一個管理Widget對象並使用簡單表繼承的Rails 4應用程序,我有專門知識Widget::FooWidget::Bar爲Rails 4中的STI模型生成通用路徑

我想通過一個WidgetsController管理我所有的Widget對象。

我有以下型號:

class Widget < ActiveRecord::Base; end 

class Widget::Foo < Widget 
    # Foo specific details... 
end 

class Widget::Bar < Widget 
    # Bar specific details... 
end 

和一個簡單的控制器:

class WidgetsController < ApplicationController 
    def index 
    @widgets = Widget.all 
    end 

    def show 
    @widget = Widget.find(params[:id]) 
    end 
end 

我的路線包括

resources :widgets, only: [:index, :show} 

在我index.html.haml我有類似:

- @widgets.each do |widget| 
    = link_to "View your widget!", [@widget] 

哪裏出問題了。

之間url_forpolymorphic_path Rails將嘗試找到一個widget_foo_path,而不是使用現有的widget_path

我寧願不添加額外的路由或控制器,我寧願不手動指定url助手。有沒有辦法告訴Rails Widget::FooWidget::Bar對象應該鏈接到使用widget_path助手?

回答

0

我結束了創建一個混合解決這個問題:

module GenericSTIRoutes 
    def initialize(klass, namespace = nil, name = nil) 
    super(klass, namespace, name) 

    superklass = klass 

    while superklass.superclass != ActiveRecord::Base 
     superklass = superklass.superclass 
    end 

    @param_key   = _singularize(superklass.name) 
    @route_key   = ActiveSupport::Inflector.pluralize(@param_key) 
    @singular_route_key = @param_key.dup 
    @route_key << "_index" if @plural == @singular 
    end 
end 

然後修改Widget.model_name如下:

def self.model_name 
    @_model_name ||= Class.new(ActiveModel::Name) do 
    include GenericSTIRoutes 
    end.new(self, nil) 
end