Skip to content

Instantly share code, notes, and snippets.

@nogtini
Forked from StevenJL/polymorp.rb
Created August 15, 2019 17:39
Show Gist options
  • Save nogtini/aa0c799b7173b9345c6202dd169d4d92 to your computer and use it in GitHub Desktop.
Save nogtini/aa0c799b7173b9345c6202dd169d4d92 to your computer and use it in GitHub Desktop.
# Suppose the AccountHolder parent class is used
# to simply have an association with an account so
# both corporations and people can have accounts.
class Account < ActiveRecord::Base
belongs_to :account_holder
end
class AccountHolder < ActiveRecord::Base
has_one :account
end
class Corporation < AccountHolder
end
class Person < AccountHolder
end
# Just use a polymorphic association instead
class Account < ActiveRecord::Base
belongs_to :account_holdable, polymorphic: true
end
class Corporation < AccountHolder
has_one :account, as: :account_holdable
end
class Person < AccountHolder
has_one :account, as: :account_holdable
end
# As such, accounts would need the polymorphic columns
# `account_holdable_type` and `account_holdable_id` which
# would describe the class as well as the primary key, respectively.
class CreateAccounts < ActiveRecord::Migration[5.0]
def change
create_table :accounts do |t|
# ... various fields
t.integer :account_holdable_id
t.string :account_holdable_type
t.timestamps
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment