4

Ok, so what I want to do, is have a template in a parent class, that loads a partial in the default template. That partial though should be specific to the derived class.

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

Then, we have the following view structure:

  • 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

In the index.html.erb we have something like this:

<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>

So, I know I can load a partial for just the item object, but what I was is a partial that is not just for the object, but a sub partial.

One option is to create a single partial in views/data_item/_col_info.html.erb that just has an if/else block to then load a separate partial, but I was hoping there was a cleaner way to do that with STI.

Also note, I can't use item.type as a way to generate the path since I have underscores in the view directory structure (type will be foodataitem, but I need foo_data_item).

alex
  • 158
  • 6
  • So, this is not my idea solution, but I did create a function in the base class called `template_path` that gets overwritten by the child classes. Still not idea, but it at least lets me do this. – alex Jun 18 '12 at 18:28

1 Answers1

1

I realize that you can't use the name of the class alone to generate the path, but you could do something like this:

item.class.name.underscore

That would be more convenient then having to add a template_path method to each class. The underscore method comes from ActiveRecord and it will convert your camel-case class name to the correct format.

Michael Frederick
  • 16,664
  • 3
  • 43
  • 58