Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 496
Wei Avatar asked Jul 16 '10 06:07

Wei


People also ask

What is single table inheritance in Rails?

Single-table inheritance (STI) is the practice of storing multiple types of values in the same table, where each record includes a field indicating its type, and the table includes a column for every field of all the types it stores.

What is Active Record :: Base in Rails?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is abstract class Rails?

Abstract classes allow for something that resembles a true interface object in Rails: the model produces holds behavior that's common to all of its children, but — because it has no data representation — it holds (and knows nothing of) the data required by its children.


1 Answers

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! 
like image 160
balexand Avatar answered Oct 02 '22 00:10

balexand