Kombajn zbożowy
Kombajn zbożowy

Reputation: 10693

Default inheritance_column name in ActiveRecord

I'm trying to change the default inheritance_column for all of my models:

# lib/change_sti_column.rb

module ChangeSTIColumn
  def self.included(base)
    base.class_eval do
      self.inheritance_column = 'runtime_class'
    end
  end
end

ActiveRecord::Base.send(:include, ChangeSTIColumn)

It seems that ActiveRecord::Base does not get it, but subclasses do!

1.9.3-p484 :005 > ActiveRecord::Base.inheritance_column
 => "type" 
1.9.3-p484 :005 > SubclassOfAR.inheritance_column
 => "type" 
1.9.3-p484 :009 > SubclassOfAR.send(:include, ChangeSTIColumn).inheritance_column
 => "runtime_class" 

So how should I correct this to make it work for base class?

Upvotes: 0

Views: 1345

Answers (2)

Tirlipirli
Tirlipirli

Reputation: 113

What about changing it globally:

ActiveRecord::Base.inheritance_column = 'runtime_class'

Or in each model:

class Class
  self.inheritance_column = :runtime_class
  ...
end

Upvotes: 1

Kombajn zbożowy
Kombajn zbożowy

Reputation: 10693

It turned out the cause was due to below definition of method ActiveRecord::Base.inheritance_column in Rails 3.2.11 that I was using:

def inheritance_column
  if self == Base
    'type' # Note this!
  else
    (@inheritance_column ||= nil) || superclass.inheritance_column
  end
end

Digging through Rails commit history I discovered that half a year ago someone had the same issue and commited a patch allowing global override of inheritance column name - hail to open source!

It is included now in both 3.2 and 4.0 branches. Had I upgraded my gems more frequently, I wouldn't have had the trouble.

Another thing that occured to me was that I needlessly patched ActiveRecord with a module, an initializer would have been enough:

# config/initializers/default_sti.rb
ActiveRecord::Base.send(:inheritance_column=, 'runtime_class')

Upvotes: 1

Related Questions