Skip to content

Instantly share code, notes, and snippets.

@nelisr
Last active June 29, 2017 17:58
Show Gist options
  • Save nelisr/9c1c07a0b660dac6b318e60726e99b1a to your computer and use it in GitHub Desktop.
Save nelisr/9c1c07a0b660dac6b318e60726e99b1a to your computer and use it in GitHub Desktop.
Implementando STI - Single Table Inheritance
Neste exemplo eu utilizarei State, City e Upload para ser os models associados.
Mostro logo abaixo um passo a passo como implementar.
1 - Gerar as migrations
## State
class CreateStates < ActiveRecord::Migration[5.0]
def change
create_table :states do |t|
t.string :name
t.timestamps
end
end
end
## City
class CreateCities < ActiveRecord::Migration[5.0]
def change
create_table :cities do |t|
t.string :name
t.timestamps
end
end
end
## Upload
class CreateUploads < ActiveRecord::Migration[5.0]
def change
create_table :uploads do |t|
t.string :picture
t.integer :modelable_id
t.string :modelable_type
t.timestamps
end
add_index :uploads, [:modelable_type, :modelable_id]
end
end
2 - criar as associações entre os models
## 1ª model - State
class State < ApplicationRecord
# association
has_many :uploads, as: :modelable, inverse_of: :modelable
end
## 2ª model - City
class State < ApplicationRecord
# association
has_many :uploads, as: :modelable, inverse_of: :modelable
end
## 3ª model - Upload
class State < ApplicationRecord
# associations
belongs_to :modelable, polymorphic: true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment