开发者

Can a model "belongs_to" either/or more than one model?

开发者 https://www.devze.com 2022-12-10 17:48 出处:网络
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:

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 BankA开发者_JS百科ccount
  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.

0

精彩评论

暂无评论...
验证码 换一张
取 消