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.
And your two (or more) other models would have a simple
has_many
relation.In your bank account you can then use
@account.people
which will give you either aMember
orTeam
object, depending of what it is.And in your
Member
orTeam
model, you can get the appropriate bank account with@member.bank_accounts
.