セッションが持続するのに問題があります。Rails 5セッションが持続しない
ユーザーをログイン/登録することはできますが、ユーザーがアプリケーションのリンクをクリックするとセッションが消えます。私はそこにある私のApplicationController内にprotect_from_forgery with: :exception
が必要だと言ったいくつかの他のStackOverflowsを読みました。また、私も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
私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