Mike Shasaco
Mike Shasaco

Reputation: 97

NoMethodError in Users#show on rails project

I keep getting a NoMethodError in Users#show.

undefined method `downcase' for nil:NilClass

I don't understand where exactly the error is when trying to use gravatar. I posted the relevant code to help assist with my question. Is there something I am missing?


show.html.erb

<h1 align="center"> Welcome to <%= @user.username %>'s page</h1>
<div class="row">
    <div class="col-md-4 col-md-offset-4 center">
        <%= gravatar_for @user %>
    </div>
</div>
<h4 align="center"><%= @user.username %>'s articles</h4>

users_controller.rb

class UsersController < ApplicationController

  def new 
    @user = User.new
  end

  def create
    @user = User.new(user_params)
    if @user.save
        flash[:success] = "Welcome to the alpha blog #{@user.username}"
        redirect_to articles_path
    else
        render 'new'
    end
  end

  def edit 
    @user = User.find(params[:id])
  end

  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
      flash[:success] = "Your account was updated successfully"
      redirect_to articles_path
    else
      render 'edit'
    end
  end 

  def show
    @user = User.find(params[:id])
  end

  private

    def user_params
      params.require(:user).permit(:username, :email, :password)
    end
end

application_helper.rb

module ApplicationHelper
    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.username, class: "img-circle")
    end
end

Upvotes: 2

Views: 148

Answers (2)

Fred Willmore
Fred Willmore

Reputation: 4604

I would guess that you're getting the error on this line:

gravatar_id = Digest::MD5::hexdigest(user.email.downcase)

which would mean that user.email is returning nil

Upvotes: 2

Gabriel Erbetta
Gabriel Erbetta

Reputation: 66

The error is on the first line of the gravatar_for method. user.email is nil, so you get this error when it tries to call downcase on a nil object. This happens because the user does not have an email.

You should check if the user has an email before you try to get his gravatar or just make sure every user has an email by putting a validation on User model.

Upvotes: 2

Related Questions