title: How to check if a user is authenticated with Devise on an AJAX call in rails?
body: <p>I have a button that allows a person to join a group (called a pod in my application).  The button uses remote: true to do an AJAX call.  I have a join table that manages the relationships between users and pods with has_many: though:.  In the join table controller I want to be able to check if the user is authenticated before that user can join a pod.  If not authenticated, the user should be taken to a log in page and then back to the page with all the pods listed.</p>
  
  <p>Right now, I've got the following code in pod_users_controller:</p>
  
  <pre><code>  before_action :user_logged_in
  
    ...
  
    private
  
    def user_logged_in
        render :js =&gt; "window.location = '#{new_user_session_path}'" unless user_signed_in?
    end
  </code></pre>
  
  <p>In my application controller I have the following code to redirect the user back to the page they were on before authenticating:</p>
  
  <pre><code>  def store_location
       session[:previous_url] = request.fullpath unless request.fullpath =~ /\/users/ 
    end
  
    def after_sign_in_path_for(resource)
        session[:previous_url] || root_path
    end
  </code></pre>
  
  <p>It's kind of works but it feels very flaky.  For example, I have another button which allows you to create a new group with an AJAX bootstrap modal.  I've tried using the same method with before_action :user_logged_in in the pods_controller file. It pops the modal without the form and then redirects.  Or when I click on the join button it will redirect me to the form to create a new pod if I just clicked the "start a pod" button before that.</p>
  
  <p>My question is, is there a better way to do what I'm doing?  How do I redirect to login before the modal pops?  I'm just learning ruby and rails so any best practices would be much appreciated.  Also, this is a total side question but in this approach I have the same method I'm calling "user_logged_in" from two controllers.  Right now I have that method at the bottom of both.  I'm assuming there's a place I can put it to make it accessible by multiple controllers from one place?</p>
  
  <p>Thank you!</p>
  
  <p>I'm on Rails 4.2 and Devise 3.4</p>