title: Check object belongs to current_user in Controller (has_and_belongs_to_many)
body: <p>I'm using devise for authentification, so I have a current_user in every controller. My models are:</p>
  
  <pre><code>class User &lt; ActiveRecord::Base
      has_many_and_belongs_to :posts
  end
  
  class Posts &lt; ActiveRecord::Base
      has_many_and_belongs_to :users
  end
  
  class PostsController &lt; ApplicationController
      before_filter :authenticate_user!
  
      def show
          @post = Post.find(params:id)
          # need to check if @post belongs to current_user here
          # ...
      end
  
      def edit
          @post = Post.find(params:id)
          # need to check if @post belongs to current_user here
          # ...
      end
  end
  </code></pre>
  
  <p>Some of the actions in <em>PostsController</em> (for instance <em>show</em> and <em>edit</em>) need to check if the Post fetched from the DB belongs to the current_user. If it doesn't, I want to show a 404 error and end the execution (just after the <em>find</em> call).</p>
  
  <p>Obviously I would like to stay DRY, so I don't want to write the same code in every action.</p>
  
  <p>I've tried to write a private method in <em>PostsController</em>, however from a private method I cannot redirect to a 404 and then interrupt the execution immediately.</p>
  
  <p>A before_filter won't work since I would be executed before each action, and I need the <em>@post</em> object which is being fetched inside each action.</p>
  
  <p>Finally I don't want to use additional gems like CanCan.</p>