Ruby-on-rails Rails:臭名昭著的“current_user”从何而来?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12719958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:50:08  来源:igfitidea点击:

Rails: where does the infamous "current_user" come from?

ruby-on-rails

提问by bigpotato

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)?

我最近一直在查看 Rails 并注意到有很多对current_user. 这仅来自Devise吗?即使我使用 Devise,我是否必须自己手动定义它?使用是否有先决条件current_user(例如会话、用户等的存在)?

采纳答案by Erik Peterson

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

它由几个 gem 定义,例如 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.

您需要将 user_id 存储在某处,通常在登录后的会话中。它还假设您的应用程序拥有并需要用户、身份验证等。

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.

这假设 User 类存在,例如#{Rails.root}/app/models/user.rb.

Updated: avoid additional database queries when there is no current user.

更新:当没有当前用户时避免额外的数据库查询。

回答by Zach Kemp

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

是的,current_user使用session. 如果您想推出自己的身份验证,您可以在应用程序控制器中执行类似的操作:

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