-
-
Save nogtini/aa0c799b7173b9345c6202dd169d4d92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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