undefined helper method
i have a problem:
undefined method `avatar_url' for #<User:0x000000040783a8>
controller:
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
in view:
...
<%for user in @users %>
<%= image_tag avatar_url(user) %>, username: <%= user.username %>, e-mail: <%= user.email %>
<% end %>
...
开发者_开发百科
Someone help me?
The key is the error message:
undefined method `avatar_url' for #<User:0x000000040783a8>
The error isn't because the helper method is undefined: the error message indicates it's a missing method in the User
class. The method defined in ApplicationController
attempts:
def avatar_url(user)
if user.avatar_url.present?
user.avatar_url
#...
You need to make sure the User
class has an avatar_url
instance method.
Better you can remove the line "helper_method :avatar_url" from the file ApplicationController.
Please see more details here. "undefined method" when calling helper method from controller in Rails
Because, you should define the helper method xxx (helper_method :xxx) in any other module/helper file. So, the line helper :all automatically include all your helper files then only you can use the line helper_method :xxx. It makes sense.
No need to define the ApplicationController methods as a helper method. You can call those methods in any controller or views in simply avatar_url().
精彩评论