ActiveRecord has_many:通过关联通过多个来源
问题描述:
我有一个自我引用has_many :through
模型has_and_belongs_to_many与另一个模型。基本上是这样的:ActiveRecord has_many:通过关联通过多个来源
class Foo << ActiveRecord::Base
has_and_belongs_to_many :bars
has_many :foo_links
has_many :foo_parents, :through => :foo_links, :foreign_key => :foo_parent_id, :class_name => "Foo"
has_many :foo_children, :through => :foo_links, :foreign_key => :foo_child_id, :class_name => "Foo"
end
我希望能够有一个foo_child
项目可以属于任何bars
其所分配,以及任何bars
到其中一个其foo_ancestors
(foo_parents
和他们的foo_parents
等)被分配。基本上,我是希望能放在一起这样的:
has_many :inherited_bars, :through => :foo_parents, :source => [:bars, :inherited_bars]
我从来没有见过这样的例子,但我想知道是否有可能有一个协会,是协会的合并从通过关联。
答
我认为has_many关联始终绑定在某处以指示关系,并允许您修改此关系。例如。您可以将新元素添加到has_many数组,并将结果保留回数据库。如果您可以将两个源合并在一起,那么您将失去按此链接行的功能。
一种可能的方法是这样的,只读的方式:
has_many :a
has_many :b
def sum
a + b
end