2011-09-17 31 views
3

我有一個問題:未定義的helper方法

undefined method `avatar_url' for #<User:0x000000040783a8> 

控制器:

class ApplicationController < ActionController::Base 
    protect_from_forgery 
    helper :all 
    helper_method :avatar_url 

    protected 

    def avatar_url(user) 
    if user.avatar_url.present? 
     user.avatar_url 
    else 
     default_url = "#{root_url}images/guest.png" 
     gravatar_id = Digest::MD5.hexdigest(user.email.downcase) 
     "http://gravatar.com/avatar/#{gravatar_id}.png?s=48&d=#{CGI.escape(default_url)}" 
    end 
    end 
end 

鑑於:

... 
<%for user in @users %> 
    <%= image_tag avatar_url(user) %>, username: <%= user.username %>, e-mail: <%= user.email %> 
<% end %> 
... 

有人幫幫我嗎?

+1

在用戶類中是否有'avatar_url'方法?錯誤來自對user.avatar_url的調用,而不是應用程序幫助方法本身。 –

+0

建議的Thx,我會檢查它。 – justi

回答

5

的關鍵是錯誤消息:

undefined method `avatar_url' for #<User:0x000000040783a8> 

的錯誤不是因爲輔助方法是不確定的:該錯誤信息表明它在User類缺少的方法。在ApplicationController嘗試定義的方法:

def avatar_url(user) 
    if user.avatar_url.present? 
    user.avatar_url 
    #... 

你需要確保User類有一個avatar_url實例方法。

+1

這是真的,我檢查了它。 – justi

-1

更好的是,您可以從文件ApplicationController中刪除「helper_method:avatar_url」行。
請在這裏看到更多的細節。 "undefined method" when calling helper method from controller in Rails

因爲您應該在任何其他模塊/幫助程序文件中定義助手方法xxx(helper_method:xxx)。所以,行輔助程序:所有自動包含所有幫助程序文件,然後只有你可以使用行helper_method:xxx。這說得通。

無需將ApplicationController方法定義爲輔助方法。你可以通過avatar_url()在任何控制器或視圖中調用這些方法。

+0

幫助程序未從控制器調用。 –

+0

@Dave Newton,請在這裏發佈錯誤信息。 –

+0

爲什麼?錯誤消息在OP中。 –