title: Query with three way association / has_many :through / join
body: <p>I'm teaching myself Rails using the guides/apis/books available but I'm having trouble understanding joins with three way/nested has_many :through associations.</p>
  
  <p>I have <strong>users</strong> connected with <strong>groups</strong> :through <strong>memberships</strong>.</p>
  
  <p>I also have <strong>posts</strong> in a many-to-many with <strong>groups</strong>. The same post can be posted to many groups + groups can have many posts.</p>
  
  <p>What I want to be able to do is for the <strong>user's</strong> home page, display all the <strong>distinct posts</strong> for the <strong>groups</strong> that the <strong>user</strong> is a member of.</p>
  
  <p>eg. current_user.groups.posts  # i wish it was this easy!!</p>
  
  <p>Here is my code.</p>
  
  <pre><code>Models:
  
  class User &lt; ActiveRecord::Base
    has_many :memberships
    has_many :groups, :through =&gt; :memberships
    has_many :posts  # as author of post
  end
  
  class Group &lt; ActiveRecord::Base
    has_many :memberships
    has_many :users, :through =&gt; :memberships
    has_and_belongs_to_many :posts
  end
  
  class Membership &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :group
  end
  
  class Post &lt; ActiveRecord::Base
    belongs_to :user
    has_and_belongs_to_many :groups
  end
  </code></pre>
  
  <p>routes.rb</p>
  
  <pre><code>Myapp::Application.routes.draw do
    get "admin/index"
    devise_for :users
  
    resources :users do
      member do
        get :groups
      end
    end
  
    resources :groups do
      member do
        get :members
        post :join
        post :leave
      end
    end
  
    resources :posts
  </code></pre>
  
  <p>home_controller.rb#index</p>
  
  <pre><code>class HomeController &lt; ApplicationController
    before_filter :authenticate_user!
  
    def index
      @user = current_user
      @groups = Group.all
      @user_groups = @user.groups
      @home_page_posts = Post.joins(:groups, :user)
    end
  end
  </code></pre>
  
  <p>This obviously just gives me a non-distinct list of all posts in all groups.</p>
  
  <p>If anyone can point me in the right direction.
  I've tried <a href="http://guides.rubyonrails.org/active_record_querying.html#joining-tables" rel="nofollow">http://guides.rubyonrails.org/active_record_querying.html#joining-tables</a> but none of the examples apply as far as I can see.</p>
  
  <p><strong>Please let me know if you need more information from me.</strong> :D</p>