title: Rails: ignoring duplicates in an nested association
body: <p>I have models <code>User</code>, <code>Team</code>, <code>Document</code>. There's a many-to-many relationship between Users and Teams, and a many-to-many relationship between Teams and Documents, using join tables called <code>TeamMembership</code> and <code>TeamDocument</code> respectively.</p>
  
  <p>The relationships in my models look like this:</p>
  
  <pre><code>class Document &lt; ActiveRecord::Base
    has_many :team_documents, dependent: :destroy
    has_many :teams, through: :team_documents
  end
  
  class User &lt; ActiveRecord::Base
    has_many :team_memberships, dependent: :destroy, foreign_key: :member_id
    has_many :teams, through: :team_memberships
    has_many :documents, through: :teams
  end
  
  class TeamDocument &lt; ActiveRecord::Base
    belongs_to :team
    belongs_to :document
  end
  
  class TeamMembership &lt; ActiveRecord::Base
    belongs_to :team
    belongs_to :member, class_name: "User"
  end
  
  class Team &lt; ActiveRecord::Base
    has_many :team_documents, dependent: :destroy
    has_many :documents, through: :team_documents
    has_many :team_memberships, dependent: :destroy
    has_many :members, through: :team_memberships
  end
  </code></pre>
  
  <p>The idea is that users can belong to many teams, a document can be associated with many teams, and users will only have access to documents that "belong" to at least one team that the user is a member of.</p>
  
  <p>Here's the question: I can use <code>User#documents</code> to retrieve a list of all the documents that this user is allowed to view. But this will return duplicates if a document is viewable by more than one team which the user is a member of. How can I avoid this?</p>
  
  <p>I know I can remove the duplicates after the fact with <code>@user.documents.uniq</code>, but as I will <strong>never</strong> want to include the duplicates in any case, is there a way I can just make <code>#documents</code> not include duplicates every time?</p>