I’m about to use STI in my Rails 2.3 application.
I’ve modeled it the following way:
Base Class:
class Tariff < ActiveRecord::Base
def self.inherited(child)
child.instance_eval do
def model_name
Tariff.model_name
end
end
super
end
def self.select_options
descendants.map { |c| c.to_s }.sort
end
end
Its subclasses:
class FlatRateTariff < Tariff
end
class TimeOfUseTariff < Tariff
has_many :tariffing_periods, :dependent => :destroy
accepts_nested_attributes_for :tariffing_periods, :allow_destroy => true
end
When I am trying to create a form_for :tariff I’m getting an undefined method `tariffing_periods’ for Tariff. How should I go about modeling this scenario? Should I put has_many association on the parent class?
STI is usually done in Rails like this:
Make sure that the Tariff table has an attribute
type:string– that’s where ActiveRecord stored the class nameYou don’t need this: (instead you can check .class )
here’s more info:
page 373 in Agile Web Development with Rails, 3rd edition
or:
http://my.safaribooksonline.com/book/web-development/ruby/9780132480345/advanced-active-record/ch09lev1sec5