Ken*_*zie 49 ruby model ruby-on-rails has-many
相对较新的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
Run Code Online (Sandbox Code Playgroud)
是否有一种简单的方法可以将has_many与2个外键一起使用,或者根据对象的性别更改外键?或者还有其他/更好的方式吗?
谢谢!
Ken*_*zie 43
在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
Run Code Online (Sandbox Code Playgroud)
ste*_*iel 17
为了改进Kenzie的答案,您可以通过定义以下内容来实现ActiveRecord Relation Person#children
:
def children
children_of_mother.merge(children_of_father)
end
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅此答案
在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
Run Code Online (Sandbox Code Playgroud)
我相信你可以使用: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
Run Code Online (Sandbox Code Playgroud)
我会在下班后确认并编辑这个答案; )
我对Rails 中的关联和(多个)外键(3.2)的回答:如何在模型中描述它们,并编写迁移只适合您!
至于你的代码,这是我的修改
class Person < ActiveRecord::Base
belongs_to :father, :class_name => 'Person'
belongs_to :mother, :class_name => 'Person'
has_many :children, ->(person) { unscope(where: :person_id).where("father_id = ? OR mother_id = ?", person.id, person.id) }, class_name: 'Person'
end
Run Code Online (Sandbox Code Playgroud)
那么还有什么问题吗?
归档时间: |
|
查看次数: |
22911 次 |
最近记录: |