Rails: where does the infamous “current_user” come from?

前端 未结 2 1292
北荒
北荒 2020-12-04 11:56

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 m

相关标签:
2条回答
  • 2020-12-04 12:12

    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
    
    0 讨论(0)
  • 2020-12-04 12:15

    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.

    0 讨论(0)
提交回复
热议问题