访问模型中的current_user [英] accessing devise current_user within model

查看:108
本文介绍了访问模型中的current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的模型中的方法

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.

我正在尝试访问一个模型中的current_user,以便通过find_or_create_by即时创建元素。 / p>

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

但我收到的错误是

NameError in EventsController#create

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


推荐答案

current_user 不能从Rails的模型文件中访问,只能使用控制器,视图和助手。

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

您应该如何传递 current_user .team_id opponent_name 这样的方法:

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

这篇关于访问模型中的current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆