Search code examples
ruby-on-railsemailcontrollerdashboardgravatar

Gravatar - Undefined method 'email' for nil:NilClass


I've set up gravatar and have got it working for my 'users/*user id goes here*'. But whenever I try to use it in dashboard/index that's whenever it gives me the error

Undefined method 'email' for nil:NilClass

My dashboard controller is :

class DashboardController < ApplicationController

  def index

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end
  end

end

Dashboard View :

<div class="dash-well">
    <div class="gravatar-dashboard">
        <%= image_tag avatar_url(@user), :class => 'gravatar' %>
        <h1 class="nuvo wtxt"><%= current_user.username.capitalize %></h1>
    </div>
</div>

My Application Helper :

module ApplicationHelper
    def avatar_url(user)
         default_url = "#{root_url}images/guest.png"
         gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
        "http://gravatar.com/avatar/#{gravatar_id}.png?s=200{CGI.escape(default_url)}"
    end

    def avatar_url_small(user)
         default_url = "#{root_url}images/guest.png"
         gravatar_id = Digest::MD5.hexdigest(user.email.downcase)
        "http://gravatar.com/avatar/#{gravatar_id}.png?s=40{CGI.escape(default_url)}"
    end
end

My user model :

class User < ActiveRecord::Base

  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :user_id, :id, :website, :bio, :skype, :dob, :age

  has_many :posts
  # attr_accessible :title, :body
end

My Dashboard Model :

class Dashboard < ActiveRecord::Base
  attr_accessible :status, :author, :email, :username, :id, :user_id, :user, :website, :bio, :skype, :dob, :age

  belongs_to :user
end

Sorry, i'm pretty new to Ruby-On-Rails!


Solution

  • Try this:

    <%= image_tag avatar_url(current_user), :class => 'gravatar' %>