Search code examples
ruby-on-railsrubyactiverecordsingle-table-inheritance

Changing type of ActiveRecord Class in Rails with Single Table Inheritance


I have two types of classes:

BaseUser < ActiveRecord::Base 

and

User < BaseUser

which acts_as_authentic using Authlogic's authentication system. This inheritance is implemented using Single Table Inheritance

If a new user registers, I register him as a User. However, if I already have a BaseUser with the same email, I'd like to change that BaseUser to a User in the database without simply copying all the data over to the User from the BaseUser and creating a new User (i.e. with a new id). Is this possible? Thanks.


Solution

  • You can just set the type field to 'User' and save the record. The in-memory object will still show as a BaseUser but the next time you reload the in-memory object will be a User

    >> b=BaseUser.new
    >> b.class # = BaseUser
    
    # Set the Type. In-Memory object is still a BaseUser
    >> b.type='User'
    >> b.class # = BaseUser
    >> b.save
    
    # Retrieve the records through both models (Each has the same class)
    
    >> User.find(1).class # = User
    >> BaseUser.find(1).class # User