3

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?

justi
  • 3,887
  • 2
  • 18
  • 24
  • 1
    Is there a `avatar_url` method in the `User` class? The error is from the call to `user.avatar_url`, not the application helper method itself. – Dave Newton Sep 17 '11 at 02:47

2 Answers2

5

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.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
-1

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().

Community
  • 1
  • 1
Mr. Black
  • 11,692
  • 13
  • 60
  • 85