Module: ActiveRecord::Inheritance
Relationships & Source Files | |
Namespace Children | |
Modules:
| |
Extension / Inclusion / Inheritance Descendants | |
Included In:
| |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
::ActiveSupport::Concern
|
|
Defined in: | activerecord/lib/active_record/inheritance.rb |
Overview
Single table inheritance
Active Record allows inheritance by storing the name of the class in a column that by default is named “type” (can be changed by overwriting Base.inheritance_column
). This means that an inheritance looking like this:
class Company < ActiveRecord::Base; end
class Firm < Company; end
class Client < Company; end
class PriorityClient < Client; end
When you do Firm.create(name: "37signals")
, this record will be saved in the companies table with type = “Firm”. You can then fetch this row again using Company.where(name: '37signals').first
and it will return a Firm object.
Be aware that because the type column is an attribute on the record every new subclass will instantly be marked as dirty and the type column will be included in the list of changed attributes on the record. This is different from non STI classes:
Company.new.changed? # => false
Firm.new.changed? # => true
Firm.new.changes # => {"type"=>["","Firm"]}
If you don't have a type column defined in your table, single-table inheritance won't be triggered. In that case, it'll work just like normal subclasses with no special magic for differentiating between them or reloading the right type with find.
Note, all the attributes for all the cases are kept in the same table. Read more: www.martinfowler.com/eaaCatalog/singleTableInheritance.html
Class Method Summary
::ActiveSupport::Concern - Extended
Instance Method Summary
DSL Calls
included
[ GitHub ]38 39 40 41 42
# File 'activerecord/lib/active_record/inheritance.rb', line 38
included do # Determines whether to store the full constant name including namespace when using STI. class_attribute :store_full_sti_class, instance_writer: false self.store_full_sti_class = true end
Instance Method Details
#initialize_dup(other)
[ GitHub ]# File 'activerecord/lib/active_record/inheritance.rb', line 223
def initialize_dup(other) super ensure_proper_type end