Skip to content

Instantly share code, notes, and snippets.

@nogtini
Forked from StevenJL/sti_bad.rb
Created August 15, 2019 17:39
Show Gist options
  • Save nogtini/a37c3fe562e3ebd4560edf818df416f3 to your computer and use it in GitHub Desktop.
Save nogtini/a37c3fe562e3ebd4560edf818df416f3 to your computer and use it in GitHub Desktop.
class Animal < ActiveRecord::Base
def eat
end
end
class Bird < Animal
def fly
end
end
class Mammal < Animal
def run
end
end
class Fish < Animal
def swim
end
end
# Animals should not be modeled using STI since their single table
# would have a lot of sparse columns (ie. mammals without wing_span and
# birds without num_of_fins)
class CreateAnimals < ActiveRecord::Migration
def change
create_table :animals do |t|
# STI required field
t.string :type
# only applicable to birds, mammals and fish will have null values
t.float :wing_span
# only applicable to fish, mammals and birds will have null values
t.integer :num_of_fins
# only applicable to mammals and birds, fish need not apply
t.integer :num_of_legs
# ... more column fields #
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment