title: Multiple INNER JOINs in a Rails has_many relationship?
body: <p>I have the following models:</p>
  
  <pre><code>class Image &lt; ActiveRecord::Base
    belongs_to :gallery
    has_many :bookmarks
    has_many :gallery_tags, :foreign_key =&gt; :gallery_id
  end
  
  class Bookmark &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :image
    has_many :gallery_tags, :through =&gt; :image, :source =&gt; :gallery_tags
  end
  
  
  class GalleryTag &lt; ActiveRecord::Base
    belongs_to :gallery
    belongs_to :tag
  end
  
  class Gallery &lt; ActiveRecord::Base
    belongs_to :provider
    has_many :images
    belongs_to :user
    has_many :gallery_tags
    has_many :tags, :through =&gt; :gallery_tags
  end
  
  class Tag &lt; ActiveRecord::Base
  end
  
  class User &lt; ActiveRecord::Base
    has_many :bookmarks
    has_many :galleries
  end
  </code></pre>
  
  <p>I'd like to be able to do</p>
  
  <pre><code>User.find(1).bookmarked_tags
  </code></pre>
  
  <p>and retrieve all tags associated with all of the user's bookmarked images via the galleries associated with the images. Tags are associated with galleries.</p>
  
  <p>The query would end up looking like this:</p>
  
  <pre><code>SELECT
    tags.*
  FROM
    tags
    INNER JOIN gallery_tags ON gallery_tags.tag_id = tags.id
    INNER JOIN images ON gallery_tags.gallery_id = images.gallery_id
    INNER JOIN bookmarks ON images.id = bookmarks.image_id
  WHERE
    bookmarks.user_id = 1
  GROUP BY
    tags.id;
  </code></pre>
  
  <p>I've tried adding</p>
  
  <pre><code>has_many :tags, :through =&gt; :gallery_tags, :foreign_key =&gt; :gallery_id
  </code></pre>
  
  <p>to Image, which causes Image.find(34).tags to result in</p>
  
  <pre><code>SELECT `tags`.* FROM `tags` INNER JOIN `gallery_tags` ON `tags`.id = `gallery_tags`.tag_id WHERE ((`gallery_tags`.gallery_id = 34))
  </code></pre>
  
  <p>(it's not using the image's gallery_id in the query), and then I've tried adding</p>
  
  <pre><code>has_many :bookmarked_tags, :through =&gt; :bookmarked_images, :source =&gt; :tags
  </code></pre>
  
  <p>to User, which causes User.find(1).bookmarked_tags to result in</p>
  
  <blockquote>
    <p>ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid
    source reflection macro :has_many :through for has_many
    :bookmarked_tags, :through => :bookmarked_images.  Use :source to
    specify the source reflection.</p>
  </blockquote>
  
  <p>So: how can I get Rails to run the query I posted with User.find(1).bookmarked_tags?</p>