我無法讓我的會話持續存在。Rails 5會話不會持續
我可以登錄/註冊用戶,但會話消失時,我的用戶點擊我的應用程序中的任何鏈接。我讀了一些其他StackOverflows是說我需要protect_from_forgery with: :exception
我ApplicationController的,這是有內..而且我需要<%= csrf_meta_tags %>
我application.html.erb佈局,這也是存在之內。所以,我有點失落。
我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
我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>
我覺得我已經到處檢查過,但我可能會錯過一些東西。
你搞亂了config/initializers/session_store.rb嗎?看看這個SO回答http://stackoverflow.com/questions/8537332/session-data-disappearing – MilesStanfield
我會開始編寫一個功能測試來檢查會話數據是否持續跨請求?該過程將幫助您弄清楚發生了什麼。 – Midwire