Rails 5个会话没有持久化

时间:2017-01-25 02:09:25

标签: ruby-on-rails ruby session ruby-on-rails-5

我无法让我的会话继续存在。

我可以正常登录/注册用户,但当我的用户点击我的应用程序中的任何链接时,会话就会消失。我在ApplicationController中读了一些其他的StackOverflows说我需要protect_from_forgery with: :exception,而且我的application.html.erb布局中也需要<%= csrf_meta_tags %>。所以,我有点失落。

我的sessions_controller.rb:

class SessionsController < ApplicationController
  def new
  end

  def create
    user = User.find_by(username: params[:session][:username])
    if user && user.authenticate(params[:session][:password])
      #Log the user in and redirect to the user's show page (for now)
      log_in user
      redirect_to user_path(user)
    else
      flash.now[:danger] = 'Invalid username/password combination'
      render 'new'
    end
  end

  def destroy
    logout
  end
end

my sessions_helper.rb:

module SessionsHelper

  # Logs in the given user.
  def log_in(user)
    session[:user_id] = user.id
  end

  # Returns the current logged-in user (if there is one).
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])
  end

  # Returns true if user is successfully logged in.
  def logged_in?
    !current_user.nil?
  end

  # Logs out current user.
  def logout
    session.delete(:user_id)
    @current_user = nil
  end
end

我的application_controller.rb:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  include SessionsHelper
end

最后,我的application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>RailsOnlineShop</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
  <% if logged_in?%>
    <%= link_to "HOME", items_path %> | <%= link_to "PROFILE", current_user %> | <%= link_to "LOGOUT", logout %>
  <% else %>
    <%= link_to "HOME", items_path %> | <%= link_to "REGISTER", new_user_path %> | <%= link_to "LOGIN", login_path %>
  <% end %>
    <%= yield %>
  </body>
</html>

我觉得我已经检查过任何有意义的东西,但我可能会遗漏一些东西。

1 个答案:

答案 0 :(得分:1)

我发现了我的问题。在我的application.html.erb中,我的注销链接不正确,并且在登录后强制我的用户立即注销。

我应该// attempt with .equals() <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script> <script> Qualtrics.SurveyEngine.addOnload(function() { var qid = Object.keys(Qualtrics.SurveyEngine.QuestionInfo)[0]; var count = "${e://Field/leaveCount}"; $(window).blur(function(){ if ( qid !== "QID3" ) { count++ Qualtrics.SurveyEngine.setEmbeddedData('leaveCount', count); }; }); }); </script> 时才<%= link_to "LOGOUT", logout %>