如何解决Ruby on Rails,重新放置Webseite或更改页面时,@ current_user设置为null
我已经创建了一个Ruby on Rails应用程序,您可以在其中创建一个帐户。当您随后登录自己时,将创建一个会话。在ApplicationController.rb中,有一个before_action,其中检查用户是否已登录,除了视图注册和欢迎。我有一个@current_user变量,当有用户登录时为true。 登录正常。当您按下登录按钮时,会创建一个会话,但是当我重新加载页面或单击指向另一页面的链接时,@ current_user等于null。 会话仍然存在,但是@current_user为false。
如何使会话持续到用户单击注销按钮?或者我该如何修复我的@current_user变量?
感谢您的帮助!
application_controller.rb
<td class="col-8">
<!-- if editable is false,show the checkbox and todo item -->
<div class="custom-control custom-checkbox" v-if="!editable">
{{ todo.item }}
</div>
<!-- if editable is true,turn item into an input so user can enter new value -->
<div v-else>
<input ref="editItem" type="text" class="form-control" :value="todo.item" @input="onInput">
</div>
</td>
<td class="col-2">
<button
class="btn btn-sm"
:class="editable ? 'btn-outline-success' : 'btn-outline-info'"
@click.prevent="editable ? onSave() : onEdit()">{{ editable ? 'save' : 'edit' }}
</button>
</td>
current_user_concern.rb
class ApplicationController < ActionController::Base
skip_before_action :verify_authenticity_token
before_action :require_login,except: [:welcome,:register,:create]
private
def require_login
unless @current_user
#reset_session
flash[:error] = "You must be logged in"
render json: {status: "You are not logged in",user: @current_user,session: session}
#render sessionhandling_welcome_path
end
end
end
sessions_controller.rb
module CurrentUserConcern
extend ActiveSupport::Concern
included do
before_action :set_current_user
end
def set_current_user
if session[:user_id]
@current_user = User.find(session[:user_id])
end
end
end
home.html.erb
class SessionsController < ApplicationController
include CurrentUserConcern
def create
user = User.find_by(email: params["user"]["email"]).try(:authenticate,params["user"]["password"])
if user
session[:user_id] = user.id
session[:expires_at] = Time.current + 1.minutes
#render "sessionhandling/home"
render json: {status: :created,logged_in: true,user: user,expires_at: session}
else
render json: {status: 401}
end
end
def logged_in
if @current_user
render json: {logged_in: true,user: @current_user}
else
render json: {logged_in: false}
end
end
def logout
reset_session
render json: {status: 200,logged_out: true}
end
end
解决方法
您缺少此部分:
application_controller.rb
class ApplicationController < ActionController::Base
include CurrentUserConcern # This is missing
skip_before_action :verify_authenticity_token
before_action :require_login,except: [:welcome,:register,:create]
private
def require_login
unless @current_user
#reset_session
flash[:error] = "You must be logged in"
render json: {status: "You are not logged in",user: @current_user,session: session}
#render sessionhandling_welcome_path
end
end
end
此外,我还将更改CurrentUserConcern
来处理#require_login
。无法保证首先运行before_action
,require_login
或set_current_user
,即使可以保证会令人困惑。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。