在模型中访问设备 current_user [英] accessing devise current_user within model
本文介绍了在模型中访问设备 current_user的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试访问模型中的 current_user,目的是使用 find_or_create_by 动态创建元素.
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.
以下是我模型中的方法
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:
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
请原谅我,如果它违反了任何 MVC 架构规则.
Pardon me, if It violates any MVC Architecture Rules.
这篇关于在模型中访问设备 current_user的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文