title: Rails / Devise: Gracefully ask user to sign in on signed-out create
body: <p>I'm continuing to tweak the <a href="http://guides.rubyonrails.org/getting_started.html" rel="nofollow">Rails Getting Started</a> project to get the authentication behavior I want.</p>
  
  <p>I want to control what is allowed and not allowed at the level of specific actions rather than for a whole controller. For example, you don't need to be signed in to view posts (<code>index</code> / <code>show</code>), but you must be signed in to access the form to submit a new post (<code>new</code>) and to get a submitted post processed (<code>create</code>).</p>
  
  <p>Since I would like people to be redirected to sign-in if they're not signed-in, and I'll be using that snippet over and over again in a million places, I put this in the application controller:</p>
  
  <pre><code>def authcheck
      unless user_signed_in?
          redirect_to new_user_session_path
      end
  end
  </code></pre>
  
  <p>For new posts, this seems to work:</p>
  
  <pre><code>def new
      authcheck #see application controller
      @post = Post.new
  end
  </code></pre>
  
  <p>But for the case where I have two tabs open and I have the first one on the new post form, but I log out on the second one, then try to submit the post on the first form, I get an error about the user being null even though it seems to me like it should have been redirected:</p>
  
  <pre><code>def create
      authcheck
      #when not signed in, causes error "undefined method 'posts' for nil:NilClass"
      @post = current_user.posts.new(post_params)
  
      if @post.save
          redirect_to @post
      else
          render 'new'
      end
  end
  </code></pre>
  
  <p>Actually, I was getting an exception page originally but I changed <code>exception</code> to <code>null_session</code> in the application controller's <code>protect_from_forgery with: :exception</code> line.</p>
  
  <p>Basically: Why isn't it redirecting to the sign-in page like it was when it was just about showing the form for a new post? And, from there, what might you suggest I should do about it?</p>