accessing devise current_user within model

狂风中的少年 提交于 2020-01-11 12:49:11

问题


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 model

def opponent_name=(name)
self.opponent = Opponent.find_or_create_by_name_and_team_id(name,current_user.team_id) if name.present?
end

but the error i am getting is

NameError in EventsController#create

undefined local variable or method `current_user' for #<Event:0x007fb575e92000>

回答1:


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



回答2:


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.




回答3:


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/




回答4:


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 🤷‍♀️ :

https://ryanbigg.com/2017/06/current-considered-harmful



来源:https://stackoverflow.com/questions/15680541/accessing-devise-current-user-within-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!