Boss Nass
Boss Nass

Reputation: 3522

accessing devise current_user within model

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>

Upvotes: 1

Views: 10402

Answers (4)

res
res

Reputation: 1225

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

Upvotes: 0

SG 86
SG 86

Reputation: 7078

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/

Upvotes: 2

Ajay
Ajay

Reputation: 4251

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.

Upvotes: 3

Erez Rabih
Erez Rabih

Reputation: 15788

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

Upvotes: 3

Related Questions