Basic example
suggest changeFirst we need a table to hold our data
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :password
t.string :type # <- This makes it an STI
t.timestamps
end
end
end
Then create the models:
class User < ActiveRecord::Base
validates_presence_of :password
# This is a parent class. All shared logic goes here
end
class Admin < User
# Admins must have more secure passwords than regular users
# We can add it here
validate :custom_password_validation
end
class Guest < User
# Lets say that we have a guest type login.
# It has a static password that cannot be changed
validates_inclusion_of :password, in: ['guest_password']
end
Guest.create still runs validations, so this record also needs a password. When the row is saved, Active Record stores it in users with type: 'Guest'.
bob = User.where(name: 'Bob').first then returns a Guest. bob.becomes(User) treats that instance as a User without changing the stored type. becomes is most useful for shared partials, routes, or controllers that expect the superclass.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents