Changing type of ActiveRecord Class in Rails with Single Table Inheritance

Wei picture Wei · Jul 16, 2010 · Viewed 16.1k times · Source

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.

Answer

balexand picture balexand · Dec 24, 2012

Steve's answer works but since the instance is of class BaseUser when save is called, validations and callbacks defined in User will not run. You'll probably want to convert the instance using the becomes method:

user = BaseUser.where(email: "[email protected]").first_or_initialize
user = user.becomes(User) # convert to instance from BaseUser to User
user.type = "User"
user.save!