accessing devise current_user within model

后端 未结 4 1612
伪装坚强ぢ
伪装坚强ぢ 2021-01-25 16:03

hi i am trying to access current_user within a model for the purpose of creating an element on the fly with find_or_create_by.

the following is the method within my mode

相关标签:
4条回答
  • 2021-01-25 16:23

    Its not a good way to access the current_user in a model, this logic belongs to the controller. But if you realy cant find a workaround you should put it into a thread. But keep in mind this is not the way how it should be build.

    https://rails-bestpractices.com/posts/2010/08/23/fetch-current-user-in-models/

    0 讨论(0)
  • 2021-01-25 16:29

    Access current_user in Model File:

    # code in Applcation Controller:
    class ApplicationController < ActionController::Base
      before_filter :global_user
    
      def global_user
        Comment.user = current_user
      end
    end
    
    #Code in your Model File :
    class Comment < ActiveRecord::Base
      cattr_accessor :user  # it's accessible outside Comment
      attr_accessible :commenter 
    
      def assign_user
        self.commenter = self.user.name
      end
    end
    

    Pardon me, if It violates any MVC Architecture Rules.

    0 讨论(0)
  • 2021-01-25 16:34

    Rails 5.2 introduced current attributes: https://api.rubyonrails.org/classes/ActiveSupport/CurrentAttributes.html

    but as always... you must have in mind that using global states like this might let to some unpredictable behaviour

    0 讨论(0)
  • 2021-01-25 16:37

    current_user is not accessible from within model files in Rails, only controllers, views and helpers.

    What you should do is to pass the current_user.team_id to the opponent_name method like this:

    def opponent_name=(name, current_user_team_id)
      self.opponent = Opponent.find_or_create_by_name_and_team_id(name,current_user.team_id) if name.present?
    end
    
    0 讨论(0)
提交回复
热议问题