简体   繁体   中英

Access Devise's current_user in Model

How do I go about accessing Devises 'current_user' object inside of a model? I want to automatically append the current users id to a record when they create something. I know that I can manually set the user_id inside of the controller but I feel it would be easier/cleaner if it was handled by the model.

Essentially, this kind of logic doesn't belong in a Model, so you're best to pass current_user in through a function in the model or on creation. This answer sums it up.

I know, I know, that's not the answer you wanted. Unfortunately, it may be cleaner looking to you, but it adds overhead to your model that you really don't want.

Many popular gems need to access the current_user in the model such as paper_trail .

Their approach starts in the controller which captures the current_user .

class ApplicationController
  before_action :set_paper_trail_whodunnit
end

Which triggers:

def set_paper_trail_whodunnit
  if ::PaperTrail.request.enabled?
    ::PaperTrail.request.whodunnit = user_for_paper_trail
  end
end

and

def user_for_paper_trail
  return unless defined?(current_user)
  current_user.try(:id) || current_user
end

After the current_user.id is saved from the controller, and an auditing action is triggered such as create.

class Widget < ActiveRecord::Base
  has_paper_trail
end

Which eventually triggers the following event.

module PaperTrail
  module Events    
    class Create < Base
      def data
        data = {
          item: @record,
          event: @record.paper_trail_event || "create",
          whodunnit: PaperTrail.request.whodunnit
        },
        # .. more create code here 
    end
  end
end

In summary, an approach would be the following.

  1. Save the current_user using a before_action in a controller
  2. Store the current_user somewhere that can be accessed later in the model, in paper_trail 's case that is PaperTrail.request.whudunnit
  3. Access your store inside the model

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM