Skip to content

Instantly share code, notes, and snippets.

@StevenJL
Last active August 15, 2019 17:39
Show Gist options
  • Save StevenJL/7b7a6ddeafc75c6ac15849dfcb42b33f to your computer and use it in GitHub Desktop.
Save StevenJL/7b7a6ddeafc75c6ac15849dfcb42b33f 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