Tutorial :Can a model “belongs_to” either/or more than one model?


Apologies if this is a slightly noob question, but looking to clarify my thoughts on this. I have a model that can EITHER belong to one model, or another. For example:

Let's say I have a Team model and I have a Member model, and both of those models can have one BankAccount.

class Team    has_many :members    has_one :bank_account  end    class Member    belongs_to :team    has_one :bank_account  end    class BankAccount    belongs_to :team, :member  end  

To me, the above makes sense, but I'd love to clarify this with some more experienced Rails people? Does Rails have any way of working out what the parent model is of any given BankAccount, baring in mind it could be one of two models? For example, if I called @bank_account.member on a Team bank account, will it throw a wobbly?

Thanks for your help.


You could use a polymorphic relationship.

Your bank account would have the polymorphic relation.

class BankAccount      belongs_to :people, :polymorphic => true  end  

And your two (or more) other models would have a simple has_many relation.

class Member      has_many :bank_accounts, :as => :people  end  

In your bank account you can then use @account.people which will give you either a Member or Team object, depending of what it is.

And in your Member or Team model, you can get the appropriate bank account with @member.bank_accounts.

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »