相对较新的rails并尝试使用具有name,gender,father_id和mother_id(2个父项)的单个Person模型来建模一个非常简单的族"树".下面基本上是我想要做的,但显然我不能重复:has_many中的孩子(第一个被覆盖).
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个外键一起使用,或者根据对象的性别更改外键?或者还有其他/更好的方式吗?
谢谢!
在IRC上找到一个似乎有效的简单答案(感谢雷达):
class Person < ActiveRecord::Base belongs_to :father, :class_name => 'Person' belongs_to :mother, :class_name => 'Person' has_many :children_of_father, :class_name => 'Person', :foreign_key => 'father_id' has_many :children_of_mother, :class_name => 'Person', :foreign_key => 'mother_id' def children children_of_mother + children_of_father end end
为了改进Kenzie的答案,您可以通过定义以下内容来实现ActiveRecord Relation Person#children
:
def children children_of_mother.merge(children_of_father) end
有关详细信息,请参阅此答案
在Person模型上使用named_scopes执行以下操作:
class Person < ActiveRecord::Base def children Person.with_parent(id) end named_scope :with_parent, lambda{ |pid| { :conditions=>["father_id = ? or mother_id=?", pid, pid]} } end
我相信你可以使用:has_one实现你想要的关系.
class Person < ActiveRecord::Base has_one :father, :class_name => 'Person', :foreign_key => 'father_id' has_one :mother, :class_name => 'Person', :foreign_key => 'mother_id' has_many :children, :class_name => 'Person' end
我会在下班后确认并编辑这个答案; )