好的,所以我想做的是在父类中有一个模板,在默认模板中加载一个部分。那个部分虽然应该特定于派生类。
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
然后,我们有以下视图结构:
- app/views/data_item/index.html.erb
 - 应用程序/视图/data_item/_col_info.html.erb
 - app/views/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>
所以,我知道我可以只为 item 对象加载一个部分,但我是一个不只是对象的部分,而是一个子部分。
一种选择是在views/data_item/_col_info.html.erb 中创建一个只有一个if/else 块的单个部分,然后加载一个单独的部分,但我希望有一种更简洁的方法来使用STI。
另请注意,我不能使用 item.type 作为生成路径的一种方式,因为我在视图目录结构中有下划线(类型将是 foodataitem,但我需要 foo_data_item)。