0

I have a self referencing has_many :through model that has another has_and_belongs_to_many with another model. Basically something like this:

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

I'd like to be able to have a foo_child item be able to belong to any bars to which it is assigned, as well as any bars to which one of its foo_ancestors (foo_parents and their foo_parents, etc) is assigned. I was basically hoping to put together something like this:

has_many :inherited_bars, :through => :foo_parents, :source => [:bars, :inherited_bars]

I've never seen such an example, but I was wondering if it is possible to have an association that is a merger of associations from a through association.

Josh Kovach
  • 7,679
  • 3
  • 45
  • 62

1 Answers1

0

I think has_many association always tied to have an id somewhere to indicate the relationship, and allows you to modify this. Eg. you can add a new element to a has_many array, and the result is persisted back to the database. If you can merge two sources together, you lose the ability to link the rows by this.

A possible approach is this, readonly way:

has_many :a
has_many :b

def sum
  a + b
end
Matzi
  • 13,770
  • 4
  • 33
  • 50