问题描述
我最近一直在浏览 Rails,注意到有很多对 current_user
的引用.这仅来自Devise吗?即使我使用 Devise,我是否必须自己手动定义它?使用 current_user
是否有先决条件(例如会话、用户等的存在)?
I've been looking around recently into Rails and notice that there are a lot of references to current_user
. Does this only come from Devise? and do I have to manually define it myself even if I use Devise? Are there prerequisites to using current_user
(like the existence of sessions, users, etc)?
推荐答案
它由几个 gem 定义,例如设计
It is defined by several gems, e.g. Devise
您需要将 user_id 存储在某处,通常是在登录后的会话中.它还假设您的应用拥有并需要用户、身份验证等.
You'll need to store the user_id somewhere, usually in the session after logging in. It also assumes your app has and needs users, authentication, etc.
通常,它类似于:
class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end
这假设 User 类存在,例如#{Rails.root}/app/models/user.rb
.
This assumes that the User class exists, e.g. #{Rails.root}/app/models/user.rb
.
更新:当没有当前用户时避免额外的数据库查询.
Updated: avoid additional database queries when there is no current user.
这篇关于Rails:臭名昭著的“current_user"在哪里?来自?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!