Search code examples
ruby-on-railsrailstutorial.orgcloud9-ide

Gravatar image not displaying


I'm working through the Michael Hartl's Ruby on Rails Tutorial, and I've added code to display a user's Gravatar image. But it doesn't display.

This is my users helper

module UsersHelper
  # Returns the Gravatar (http://gravatar.com/) for the given user.
  def gravatar_for(user)
    gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
    gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
    image_tag(gravatar_url, alt: user.name, class: "gravatar")
  end
end

And this is my show.html.erb

<% provide(:title, @user.name) %>
<div class="row">
  <aside class="col-md-4">
    <section class="user_info">
      <h1>
        <%= gravatar_for @user %>
        <%= @user.name %>
      </h1>
    </section>
  </aside>
</div>

This is the code when i inspect the element

    <img alt="humber" class="gravatar" src="https://secure.gravatar.com/avatar/8e92292186fbb306e253b08d0f3eb993">
    humber

this is the image


Solution

  • your code is correct, maybe the user that you are using has no email, or the email don't have an image in gravatar. I would suggest that you validate if the user have an email

    def gravatar_for(user)
        if user.email?
            gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
            gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}"
            image_tag(gravatar_url, alt: user.name, class: "gravatar")
        else
            image_tag("/img/avatar_default.png", alt: user.name, class: "gravatar")
        end
    end