Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails partials with single-table inheritance

I want to use partials in rails along with single-table inheritance. I currently have this working:

render partial: @vehicle

# which renders the relevant view, depending on object type, eg:
#   views/trucks/_truck.haml
#   views/car/_car.haml

I want to leave these default views in place, and create an additional compact view for each object, perhaps like this

# example code only, I want to write something like:
render partial: 'compact', locals: {vehicle: @vehicle}

# and then have this render (for example) with
#   views/trucks/_compact.haml
#   views/car/_compact.haml

I can happily rename things or change the file names or locations, but what is the simplest way to support two kinds of views (compact and default)?

There will be many more classes later, so looking for very clean, elegant code.

(rails 3.0.5+ on ruby 1.9.2)

like image 830
Peter Avatar asked May 03 '11 07:05

Peter


People also ask

What is single-table inheritance in rails?

Single-table inheritance (STI) is the practice of storing multiple types of values in the same table, where each record includes a field indicating its type, and the table includes a column for every field of all the types it stores.

How does the single-table inheritance work?

In Single-Table Inheritance (STI), many subclasses inherit from one superclass with all the data in the same table in the database. The superclass has a “type” column to determine which subclass an object belongs to. In a polymorphic association, one model “belongs to” several other models using a single association.

What is a standard prerequisite for implementing single-table inheritance?

To get started with STI from a database perspective, all you need to do is add a field called “type” to the table. Rails takes this type field and applies the name of the sub-classes that inherit from the class for which the table is named as the value for a row of data.


1 Answers

To get exactly what you asked for you should do this:

render partial: "#{@vehicle.type.tableize}/#{@vehicle.type.underscore}", object: @vehicle

and you will get rendered:

views/trucks/_truck.html.haml

and the object will be accessible as:

@truck
like image 189
Jan Minárik Avatar answered Sep 25 '22 16:09

Jan Minárik