Rails: 臭名昭著的“ current_user”从何而来?

我最近一直在研究 Rails,注意到有很多关于 current_user的参考。这只是德维斯说的吗?即使我使用 Devise,我也必须自己手动定义它吗?使用 current_user是否有先决条件(如会话、用户等的存在) ?

57797 次浏览

It is defined by several gems, e.g. Devise

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.

Typically, it's something like:

class ApplicationController < ActionController::Base
def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end
end

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.

Yes, current_user uses session. You can do something similar in your application controller if you want to roll your own authentication:

def current_user
return unless session[:user_id]
@current_user ||= User.find(session[:user_id])
end