Rails 模型 has_many 具有多个foreign_keys
对 Rails 来说相对较新,并尝试使用具有姓名、性别、father_id 和 mother_id(2 个父母)的单个 Person 模型来建模非常简单的家庭“树”。 下面基本上是我想做的,但显然我不能在 has_many 中重复 :children (第一个被覆盖)。
class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end
有没有一种简单的方法可以将 has_many 与 2 个外键一起使用,或者可以根据对象的性别更改外键? 或者还有另一种/更好的方法吗?
谢谢!
Relatively new to rails and trying to model a very simple family "tree" with a single Person model that has a name, gender, father_id and mother_id (2 parents). Below is basically what I want to do, but obviously I can't repeat the :children in a has_many (the first gets overwritten).
class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children, :class_name => 'Person', :foreign_key => 'mother_id'
has_many :children, :class_name => 'Person', :foreign_key => 'father_id'
end
Is there a simple way to use has_many with 2 foreign keys, or maybe change the foreign key based on the object's gender? Or is there another/better way altogether?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
在 IRC 上找到了一个似乎有效的简单答案(感谢 Radar):
Found a simple answer on IRC that seems to work (thanks to Radar):
要改进 Kenzie 的答案,您可以通过定义
Person#children
来实现 ActiveRecord 关系例如:请参阅此答案了解更多详细信息
To improve on Kenzie's answer, you can achieve an ActiveRecord Relation by defining
Person#children
like:see this answer for more details
在 Person 模型上使用named_scopes
做这个:
Used named_scopes over the Person model
do this:
我相信你可以使用 :has_one 实现你想要的关系。
下班后我会确认并编辑这个答案; )
I believe you can achieve the relationships you want using :has_one.
I'll confirm and edit this answer after work ; )
我对 rails 中的关联和(多个)外键(3.2)的回答:如何在模型中描述它们,并编写迁移 只适合您!
至于你的代码,这是我的修改
所以还有问题吗?
My answer to Associations and (multiple) foreign keys in rails (3.2) : how to describe them in the model, and write up migrations is just for you!
As for your code,here are my modifications
So any questions?
我更喜欢使用范围来解决这个问题。 像这样:
这个技巧可以很容易地在没有使用实例的情况下获得孩子:
I prefer to use scopes for this issue. Like this:
This trick make it easy to get children without use instances:
不是所述一般问题的解决方案(“has_many 具有多个外键”),但是,鉴于一个人可以是母亲或父亲,但不能同时是两者,我会添加一个
gender
列并与Not a solution to the general question as stated ("has_many with multiple foreign keys"), but, given a person can either be a mother or a father, but not both, I would add a
gender
column and go with我一直在寻找相同的功能,如果您不想返回数组而是
ActiveRecord::AssociationRelation
,您可以使用<<
而不是>+。
(请参阅 ActiveRecord 文档)
I was looking for the same feature, if you don't want to return an array but a
ActiveRecord::AssociationRelation
, you can use<<
instead of+
.(See the ActiveRecord documentation)