【问题标题】:Rails 3 STI load derived partialRails 3 STI 负载派生的部分
【发布时间】:2012-06-13 15:04:33
【问题描述】:

好的,所以我想做的是在父类中有一个模板,在默认模板中加载一个部分。那个部分虽然应该特定于派生类。

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
  • app/views/data_item/_col_info.html.erb
  • app/views/foo_data_item/_col_info.html.erb
  • app/views/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)。

【问题讨论】:

  • 所以,这不是我的想法解决方案,但我确实在名为template_path 的基类中创建了一个函数,该函数被子类覆盖。仍然不知道,但它至少让我可以做到这一点。

标签: ruby-on-rails-3.1 single-table-inheritance


【解决方案1】:

我意识到你不能单独使用类的名称来生成路径,但你可以这样做:

item.class.name.underscore

这样会更方便,然后必须为每个类添加一个template_path 方法。 underscore method 来自 ActiveRecord,它会将您的驼峰类名称转换为正确的格式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多