<p>I have a two tables joined with a join table - this is just pseudo code:</p>

<pre><code>Library
Book
LibraryBooks
</code></pre>

<p>What I need to do is if i have the id of a library, i want to get all the libraries that all the books that this library has are in.</p>

<p>So if i have Library 1, and Library 1 has books A and B in them, and books A and B are in Libraries 1, 2, and 3, is there an elegant (one line) way todo this in rails?</p>

<p>I was thinking:</p>

<pre><code>l = Library.find(1)
allLibraries = l.books.libraries
</code></pre>

<p>But that doesn't seem to work. Suggestions?</p>

[{'answer_id': 79646, 'author': 'Jim Puls', 'author_id': 6010, 'author_profile': 'https://Stackoverflow.com/users/6010', 'pm_score': 2, 'selected': False, 'text': '<p>Perhaps:</p>\n\n<pre><code>l.books.map {|b| b.libraries}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>l.books.map {|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>if you want it all in a flat array.</p>\n\n<p>Of course, you should really define this as a method on Library, so as to uphold the noble cause of encapsulation.</p>\n'}, {'answer_id': 79770, 'author': 'bouchard', 'author_id': 14843, 'author_profile': 'https://Stackoverflow.com/users/14843', 'pm_score': 2, 'selected': False, 'text': '<p>If you want a one-dimensional array of libraries returned, with duplicates removed.</p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n'}, {'answer_id': 81287, 'author': 'Ben Scofield', 'author_id': 6478, 'author_profile': 'https://Stackoverflow.com/users/6478', 'pm_score': 2, 'selected': False, 'text': "<p>One problem with </p>\n\n<pre><code>l.books.map{|b| b.libraries}.flatten.uniq\n</code></pre>\n\n<p>is that it will generate one SQL call for each book in l. A better approach (assuming I understand your schema) might be:</p>\n\n<pre><code>LibraryBook.find(:all, :conditions =&gt; ['book_id IN (?)', l.book_ids]).map(&amp;:library_id).uniq\n</code></pre>\n"}, {'answer_id': 81752, 'author': 'Ryan Bigg', 'author_id': 15245, 'author_profile': 'https://Stackoverflow.com/users/15245', 'pm_score': 4, 'selected': True, 'text': '<pre><code>l = Library.find(:all, :include =&gt; :books)\nl.books.map { |b| b.library_ids }.flatten.uniq\n</code></pre>\n\n<p>Note that <code>map(&amp;:library_ids)</code> is slower than <code>map { |b| b.library_ids }</code> in Ruby 1.8.6, and faster in 1.9.0.</p>\n\n<p>I should also mention that if you used <code>:joins</code> instead of <code>include</code> there, it would find the library and related books all in the same query speeding up the database time. <code>:joins</code> will only work however if a library has books. </p>\n'}]
['https://Stackoverflow.com/questions/79632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4322/']