Rails Single Table Inheritance: changing inheritance_column name
I was recently told that the default “type” column use for inheritance_column in ActiveRecord’s STI is deprecated. The reason is “type” is also used as an alias for Object#class and there may be other reasons.
I wanted to see how it would behave if I just applied inheritance_column override in Model without any migration changes.
So, I changed my User class from this:
class Class ... end
to:
class Class self.inheritance_column = :user_type ... end
Checking out how it behaved in script/console gave me this:
>> ActiveRecord::Base.logger = Logger.new(STDOUT) >> User.count # SQL (0.4ms) SET NAMES 'utf8' # SQL (0.3ms) SET SQL_AUTO_IS_NULL=0 # User Columns (38.0ms) SHOW FIELDS FROM `users` # SQL (13.5ms) SELECT count(*) AS count_all FROM `users` => 9 >> Child.count # Child Columns (2.7ms) SHOW FIELDS FROM `users` # SQL (0.2ms) SELECT count(*) AS count_all FROM `users` => 9 >> Parent.count # VriUser Columns (2.6ms) SHOW FIELDS FROM `users` # SQL (0.2ms) SELECT count(*) AS count_all FROM `users` => 9
They all gave count of 9, and as you can see, there is no where clause for the type/user_type as you expect. Obviously, the table didn’t change (as you would expect).
Time to add migration:
class ChangeUserTypeColumnName < ActiveRecord::Migration def self.up rename_column :users, :type, :user_type end def self.down rename_column :users, :user_type, :type end end
After this, it all worked as expected.
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.






When you said:
self.interitance_column = :user_type
Did you mean:
self.inheritance_column = :user_type ?
Rodrigo Flores
26 May 10 at 6:33 pm
Fixed. Thanks!
Sharad
27 May 10 at 11:12 am