This is good timing. I need to know about this stuff tomorrow to help a colleague out. Rails Polymorphic Associations were a bit mysterious to me and so I didn't use them when I first started with Rails but the time has come to put them to work.
First, the scenario:
A Player and a Corporation both may have many Wallet Balance Entries and a Wallet Balance Entry belongs to either a Player or a Corporation.
The Models are this:
-
# app/models/wallet_balance_entry.rb
-
class WalletBalanceEntry <ActiveRecord::Base
-
belongs_to :wallet_balance_owner, :polymorphic => true
-
end
And (just the Player model)
-
# app/models/player.rb
-
class Player <ActiveRecord::Base
-
has_many :wallet_balance_entries, :as => :wallet_balance_owner
-
end
The relevant bits of the WalletBalanceEntry schema look like this:
-
create_table "wallet_balance_entries", :force => true do |t|
-
t.string "wallet_balance_owner_type"
-
t.integer "wallet_balance_owner_id"
Note that wallet_balance_owner_type and wallet_balance_owner_id match the name that the Player model specifies with :as => :wallet_balance_owner. The Corporation model will have the exact same line and it will work! Should Alliances come to have many wallet balance entries the Alliance model will have this same line as well.

