2

我想在我的‘团队’的模式来写的方法,但CURRENT_USER正显示出此错误未定义的局部变量或方法`CURRENT_USER“使用设计和轨道3.2

未定义的局部变量或方法`CURRENT_USER”为#

def set_default_url 
    if current_user.id == self.user_id 
    "/assets/default_black_:style_logo.jpg" 
    else 
    "/assets/default_:style_logo.jpg" 
    end 
end 

方法current_user对其他模型和控制器工作正常。我正在像这样调用这个方法。

has_attached_file :logo, :styles => { 
    :medium => "200x200#", 
    :thumb => "100x100#", 
    :small => "50x50#" 
}, 
:default_url => :set_default_url 

我使用rails 3.2,ruby 1.9.3和devise 3.1。这似乎很简单,但我不明白错在哪里。如果有人帮我在这里,我会非常感激。

+0

你可能想看看这个http://stackoverflow.com/questions/1568218/access-to-current-user-from-within-a-model-in-ruby-on -rails – Santhosh 2015-03-02 07:29:04

+0

您是否已将'User'模型与'Team'模型关联? – 2015-03-02 07:30:52

+0

@GaganGami是的!当然 – techdreams 2015-03-02 07:33:52

回答

13

current_user是不提供任何模型,访问current_user模型做这个

在应用程序控制器

before_filter :set_current_user 

def set_current_user 
    Team.current_user = current_user 
end 

Team模型中加入这一行

cattr_accessor :current_user 

祝贺,现在每个型号都有current_user,为了让当前用户每次使用下面的行ere

Team.current_user 

注意:添加上面提到的行后重新启动服务器!

现在在你的问题,你可以使用它像

def set_default_url 
    if Team.current_user.id == self.user_id 
    "/assets/default_black_:style_logo.jpg" 
    else 
    "/assets/default_:style_logo.jpg" 
    end 
end 

希望这有助于!

+0

即使我登录,Team.current_user返回nil – techdreams 2015-03-02 08:04:12

+0

糟糕,我很抱歉,我错过了一行,在应用程序控制器中添加了这行'before_filter:set_current_user',我编辑了答案 – RSB 2015-03-02 08:18:09

+0

感谢它的工作。 – techdreams 2015-03-02 08:24:51

1

如果您正在使用它只有一次不是同时调用此方法通CURRENT_USER作为参数,像

has_attached_file :logo, :styles => { 
    :medium => "200x200#", 
    :thumb => "100x100#", 
    :small => "50x50#" 
}, 
:default_url => :set_default_url(current_user) 

,并在模型

def set_default_url(current_user) 
    if current_user.id == self.user_id 
    "/assets/default_black_:style_logo.jpg" 
    else 
    "/assets/default_:style_logo.jpg" 
    end 
end 

如果你不希望上面的步骤,然后按照下列

前往用户模型

def self.current_user 
    Thread.current[:user] 
end 

def self.current_user=(user) 
    Thread.current[:user] = user 
end 

然后去应用控制器

before_filter :set_current_user 

def set_current_user 
    User.current_user = current_user 
end 

现在,我们可以很容易地在任何模型获取CURRENT_USER不仅在团队

只是给作为User.current_user所以在你的代码

def set_default_url 
    if User.current_user.id == self.user_id 
    "/assets/default_black_:style_logo.jpg" 
    else 
    "/assets/default_:style_logo.jpg" 
    end 
end 

因此,请使用它。

希望它能很好地解决您的问题。免费使用任何型号

User.current_user获取当前用户 用户。current_user =分配当前用户。

感谢

相关问题