Swap between STI classes in Rails
Rails allows you to swap between single table inheritance classes with the becomes
method. This method creates a new instance of the desired class, and passes the attributes from the original record to the new instance.
So if I have two classes, User
and Admin
, where Admin
inherits from User
:
class User
# ...
end
class Admin < User
# ...
end
I can change between the two classes using becomes
:
user = User.first # returns an instance of the User class
user.class # => User
user.id # => 1
user.name # => Joe Hashrocket
admin = user.becomes(Admin) # returns an instance of the Admin class
admin.class # => Admin
admin.id # => 1
admin.name # => Joe Hashrocket
Tweet