Note that there are some explanatory texts on larger screens.

plurals
  1. POMerging the Associations of a Parent, its Children and it's Childrens' Children with Rails3
    text
    copied!<p>I have a model <code>Foo</code>. <code>Foo</code> has many children of type <code>FooChild</code>. <code>FooChild</code> has many <code>FooChildChild</code>. <code>Foo</code>, <code>FooChild</code> and <code>FooChildChild</code> all have and belong to many <code>Bar</code>. I want to create a method or scope on <code>Foo</code> that will return all of the <code>Bar</code> associated with it and it's child associations. I currently have something like the following on the <code>Foo</code> model.</p> <pre><code>def foo_child_bars b = [] self.foo_childs.includes(:bar).collect{|fc| b += fc.bar} b.uniq end def foo_child_child_bars b = [] self.foo_childs.includes(:foo_child_childs).collect{|fcc| b += fcc.bar} b.uniq end def all_bars (self.bars + self.foo_child_bars + self.foo_child_child_bars).uniq end </code></pre> <p>So now I can call <code>@foo.all_bars</code> and this works and I don't get duplicates because of the <code>.uniq</code> method.</p> <p>I imagine that this sort of operation is rather inefficient due to the fact that I'm performing three separate queries. Ideally I'd like to do a single query with a <code>UNION</code> or something so that the database does the heavy lifting of ensuring only unique records are returned and I'm doing as few queries as possible.</p> <p>I'm also curious if there is a way to use <code>includes()</code> on a nested association such that <code>foo_child_child_bars()</code> could include the <code>:bars</code> which are associated with all of the <code>:foo_child_childs</code> which are being included.</p> <p><code>Bar</code> in this reduction represents a table <code>'images'</code> which has <a href="https://github.com/jnicklas/carrierwave" rel="nofollow">CarrierWave</a> set up on the <code>Image</code> model for managing uploaded images. I'm almost positive that there is a gem out there that would probably simplify this whole thing, but I'd rather just make what I have work and tackle that gem implementation later as it will likely involve a lot of complicated table migrations and refactoring.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload