title: Getting values through relational table
body: <p>In my app I have a page which render all the projects in the database. What I want is to be able to filter the results, for example by showing only the once in which the user is a member.</p>
  
  <p>Below is from my projects controller, where I want to do exactly that (show only projects where the user is a member). What do is to first get all the projects from 'ProjectUser' where the user_id is found. Then I want to use this array to retrieve all the relevant projects from the table 'Projects', with the use of @user_is_member.project_id.</p>
  
  <p>This does not work because it only give me ONE project, not all.   </p>
  
  <p>How can I change the code so I accomplish what I want?</p>
  
  <p><strong>The code:</strong></p>
  
  <pre><code>@user_is_member = ProjectsUser.where(:user_id =&gt; current_user.id)
  
  @user_is_member.each do |member|
      @projects = Project.where(:id =&gt; member.project_id)
  end
  </code></pre>
  
  <h2>Tables:</h2>
  
  <p><strong>projects_users:</strong></p>
  
  <pre><code>project_id
  user_id
  </code></pre>
  
  <p><strong>projects:</strong></p>
  
  <pre><code>id
  ...non relevant fields...
  </code></pre>
  
  <h2>Models:</h2>
  
  <p><strong>User model:</strong></p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    has_many :project_users
    has_and_belongs_to_many :projects
  end
  </code></pre>
  
  <p><strong>Project model:</strong></p>
  
  <pre><code>class Project &lt; ActiveRecord::Base
    has_and_belongs_to_many :users # =&gt; , :class_name =&gt; 'User'
  
    belongs_to :user
  end
  </code></pre>
  
  <p><strong>ProjectUser model:</strong></p>
  
  <pre><code>class ProjectsUser &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :project
  end
  </code></pre>
  
  <p><strong>Note:</strong> current_user is the currently logged in user (which has access to all the user fields, e.g "id")</p>