可以在模型" belongs_to的"要么/或超过一个模型吗? [英] Can a model "belongs_to" either/or more than one model?
问题描述
道歉,如果这是一个稍微noob问题,但希望澄清我对这个想法。我有一个可以属于一个模型或其他模型。例如:
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:
让我们说我有一个团队模式,我有一个会员模型,这两个模型可以有一个的BankAccount。
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
在我看来,以上是有道理的,但我喜欢用一些比较有经验的Rails人澄清这一点?是否导轨具有工作了父模型是任何特定的BankAccount什么,记住它裸露可以是两个车型之一的方法吗?例如,如果我叫上一组银行账号@ bank_account.member,将它抛出一个不稳定?
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?
感谢您的帮助。
推荐答案
您可以使用多态性关系。
您的银行帐户将有多态性关系。
Your bank account would have the polymorphic relation.
class BankAccount
belongs_to :people, :polymorphic => true
end
和你的两个(或更多)等车型将有一个简单的的has_many
关系。
And your two (or more) other models would have a simple has_many
relation.
class Member
has_many :bank_accounts, :as => :people
end
在您的银行帐户就可以使用 @ account.people
,这将给你无论是成员
或团队
的对象,这取决于它是什么。
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.
而在你的成员
或团队
模式,你可以用 @ member.bank_accounts
。
And in your Member
or Team
model, you can get the appropriate bank account with @member.bank_accounts
.
这篇关于可以在模型" belongs_to的"要么/或超过一个模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!