Basic example

suggest change

First 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents