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

梦想与她 提交于 2020-01-01 04:26:30

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/1700800/can-a-model-belongs-to-either-or-more-than-one-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!