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.
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.
ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With