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
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/
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.
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
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