title: Restrict routes to certain users in Rails app
body: <p>In my rails v4 app, users belong to a single group. </p>
  
  <pre><code>class User &lt; ActiveRecord::Base
    belongs_to :group
    ...
  </code></pre>
  
  <p>Each group can have many projects, </p>
  
  <pre><code>class Group &lt; ActiveRecord::Base
    has_many :projects
    has_many :users
    ...
  </code></pre>
  
  <p>Each project can have many experiments, in a one to many relationship.</p>
  
  <p>In my routes, I have:</p>
  
  <pre><code>resources :projects do
      resources :experiments do
        ...
      end
    end
  </code></pre>
  
  <p>What I'd like to do is only allow users to access projects and experiments if the project has the same group_id as the user (i.e. if user enters a project id parameter in the projects#show route for a project outside of their group, it will not be displayed). Is there a clean way to implement this without having to do multiple checks in the view?</p>