Topic: Definitive Guide to Single Table Inheritance
After trying to implement this in my project I am realizing just how scant and misleading the docs are on this topic. This thread is more of a request than a tutorial and I am hoping that some of you more experienced Rails folk will fill out the missing pieces of the puzzle.
To make your jobs easier, I will cover what I do know...
When to use STI:
This structure is best used for models that have identical, or very similar attributes. A perfect example would be a table called cars. You can have columns like horsepower, gas_mileage, price etc. since all cars are basically categorized in the same fashion, STI is a perfect fit.
On the other hand, if your subclasses are pretty different from each other, then they deserve their own table.
Rails supports STI out of the box. All you need to do is create a table with a column called "type". You can override this convention and use a differnt name for the column, but for simplicity's sake we wont go there.
Here is the migration file.
class CreateCars < ActiveRecord::Migration
create_table :cars do |t|
t.column :type, :string
t.column :name, :string
t.column :price, :string
t.column :gas_mileage, :string
t.column :horse_power, :string
Once the table has been created, it's time to make our model file, car.rb:
class Car < ActiveRecord::Base
class Ford < Car
class Toyota < Car
With our Model ready to go its time to set up CarController.rb.
And this is where I get completely lost. Niether the Rails API or the AWD book offer much help in this department, and the Wiki's code is outdated ( Tons of @params and no RESTful routes) Also, this bit of view code:
<%= hidden_field_tag "option_type", @option[:type] %>
Is completely worthless and throws up an error. Some people have commented this on the wiki but no one has responded.
Of course I could just throw my hands up and use multiple tables, but I know this is the proper way to do it so I hope someone will be able to pick up the baton and run with this tutorial.
THE KEY QUESTIONS:
1. How do we specify the subclass through a form? Should it be inside the form_for statement? A hidden input?
2. How do we set up the find and create methods for subclasses in the model and then reference them in the controller?
3. How do we write the index and delete actions?