Tatva-Artha

meaning of "it"

Rails Single Table Inheritance: changing inheritance_column name

with 2 comments

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.

http://www.tatvartha.com/wp-content/plugins/sociofluid/images/digg_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/reddit_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/stumbleupon_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/delicious_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/google_16.png http://www.tatvartha.com/wp-content/plugins/sociofluid/images/twitter_16.png

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

Written by Sharad

August 5th, 2009 at 3:45 pm

Posted in All

2 Responses to 'Rails Single Table Inheritance: changing inheritance_column name'

Subscribe to comments with RSS or TrackBack to 'Rails Single Table Inheritance: changing inheritance_column name'.

  1. 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

  2. Fixed. Thanks!

    Sharad

    27 May 10 at 11:12 am

Leave a Reply