2012-06-13 44 views
4

好吧,所以我想要做的是在父類中有一個模板,它在默認模板中加載一個部分。這部分雖然應該是特定於派生類。Rails 3 STI負載派生部分

def class DataItem < ActiveRecord::Base 
    def value 
    # do something fancy here 
    end 
end 

def class FooDataItem < DataItem 
    def value 
    "foo" 
    end 
end 

def class BarDataItem < DataItem 
    def value 
    "bar" 
    end 
end 

然後,我們有以下的視圖結構:

  • 應用/視圖/ data_item/index.html.erb
  • 應用/視圖/ data_item/_col_info.html.erb
  • 應用程序/視圖/ foo_data_item/_col_info.html.erb
  • 應用/視圖/ bar_data_item/_col_info.html.erb

在index.html.erb,我們有這樣的事情:

<table> 
    <thead> 
    <tr> 
     <th>Key</th> 
     <th>Value</th> 
    </tr> 
    </thead> 
    <tbody> 
    <% @dataItems.each do |item| %> 
    <tr> 
     <td><%= render :partial, item + "/col_info", :locals => { :item => item } %> 
     <td><%= item.value %> 
    </tr> 
    <% end %> 
    </tbody> 
</table> 

所以,我知道我可以加載部分只是該項目的對象,但我是一個局部的,是不是隻爲對象,但一個子部分。

一種選擇是在views/data_item/_col_info.html.erb中創建一個只包含if/else塊的單個部分,然後加載一個單獨的部分,但我希望有一個更清晰的方法來做到這一點STI。

另外請注意,我不能使用item.type作爲生成路徑的方法,因爲我在視圖目錄結構中有下劃線(類型爲foodataitem,但我需要foo_data_item)。

+0

所以,這不是我的想法解決方案,但我確實在基類「template_path」中創建了一個被子類覆蓋的函數。仍然不知道,但它至少讓我這樣做。 – alex

回答

1

我意識到,你不能使用類的名稱單獨產生的路徑,但你可以做這樣的事情:

item.class.name.underscore 

這會更方便,然後還要加一個template_path方法到每個班級。 underscore method來自ActiveRecord,它會將您的駱駝案例類名稱轉換爲正確的格式。