accessing devise current_user within model

后端 未结 4 1615
伪装坚强ぢ
伪装坚强ぢ 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: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.

提交回复
热议问题