spinlock
spinlock

Reputation: 3947

How can I create a Polymorphic Ruby Method?

I have a class -- AccountGroup -- which has a polymorphic relation to various Account classes (i.e. AwordsAccount, BingAccount, etc...). I've defined a helper method -- accounts -- that aggregates all of the different account types:

def accounts
  adwords_accounts + bing_ads_accounts + facebook_accounts + linkedin_accounts
end

Now, I'd like to extend this method so that I can use it to add accounts as well as list them:

account_group.accounts << an_adwords_account

which should call:

account_group.adwords_accounts << an_adwords_account

under the hood. How do I differentiate between calling the method with the modifier << vs. calling it without the modifier?

Thanks!

Upvotes: 0

Views: 203

Answers (1)

Patrick Oscity
Patrick Oscity

Reputation: 54674

Here's how I would implement this. The Account model uses single table inheritance and has a type column that distinguishes between the different account types:

class Account < ActiveRecord::Base
  belongs_to :account_group
end

class AdwordsAccount < Account
end

class BingadsAccount < Account
end

class FacebookAccount < Account
end

class LinkedinAccount < Account
end

In your AccountGroup model you can then create associations to all of these without any problems:

class AccountGroup < ActiveRecord::Base
  has_many :accounts
  has_many :adwords_accounts
  has_many :bingads_accounts
  has_many :facebook_accounts
  has_many :linkedin_accounts
end

Now everything works as expected and accounts contains all of the other types combined. You might need to call reload on the other associations when you add/remove accounts, but i'm not sure about that. Just try it out.

Upvotes: 1

Related Questions