【问题标题】:Rails Session not persisting after browser refresh浏览器刷新后Rails Session不会持续存在
【发布时间】:2015-11-15 19:45:29
【问题描述】:

在应用程序内导航和重定向都很好,它只是在浏览器刷新时用户必须重新登录。我只希望会话在浏览器关闭而不是刷新时过期..

我的 session_store.rb

Rails.application.config.session_store :cookie_store, key:
'_workspace_session'

我的会话控制器新建和创建操作:

def new

end


def create
    merchant = Merchant.find_by(email: params[:email])

    if merchant && merchant.authenticate(params[:password])
        session[:merchant_id] = merchant.id
        log_in(merchant)
        flash[:success] = "You were logged in successfully"
        redirect_to merchant_path(merchant.id)
    else
        flash.now[:danger] = "Snap! either your email or password is 
        incorrect. Try again"
        render 'new'
    end

end

【问题讨论】:

    标签: ruby-on-rails session authentication


    【解决方案1】:

    这可能是因为您没有会话助手来添加登录商家凭据的 cookie 并在每次重新加载页面时检查它们: 首先,将您的 sessions_helper.rb 添加到您的主控制器:

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

    这是您的会话助手:

     module SessionsHelper
    
      # Returns the user corresponding to the remember token cookie.
      def current_merchant
        if (merchant_id = session[:merchant_id])
          @current_merchant ||= Merchant.find_by(id: merchant_id)
        elsif (merchant_id = cookies.signed[:merchant_id])
          merchant= Merchant.find_by(id: merchant_id)
          if merchant && merchant.authenticated?(cookies[:remember_token])
            log_in merchant
            @current_user = merchant
          end
        end
      end
    
     #logs the merchant in.I don't know what your log_in method does there in the    question, if it does the same, you are doing it two times.
    
     def log_in(merchant)
        session[:merchant_id] = merchant.id
     end
    
    
    end
    

    Adapted from RailsTutorial

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 2012-08-31
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 2016-09-10
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      相关资源
      最近更新 更多