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 =分配當前用戶。

感謝

相關問題