ruby-on-railsrubyruby-on-rails-4devisepaperclip

Undefined method `avatar' for nil:NilClass


I'm trying to print an image using the Paperclip gem.

When I print using views/devise/edit.html.rb everything looks good but when I want print in views/layout/application.html.rb I'm getting this error in console:

ActionView::Template::Error (undefined method `avatar' for nil:NilClass):
     7:   <%= csrf_meta_tags %>
     8: </head>
     9: <body>
    10: <%= image_tag @user.avatar.url(:thumb) %>
    11: <%= yield %>
    12: 
    13: </body>
  app/views/layouts/application.html.erb:10:in `_app_views_layouts_application_html_erb___4291648939640547438_70254980514000'

This is User.rb:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

has_attached_file :avatar, :styles => { :medium => ["300x300>"], :thumb => ["100x100>"], :page => ["800"] }


end

This is application_controller.rb:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
 before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation) }
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :email, :password, :password_confirmation, :current_password, :avatar) }


  end


end

Solution

  • @user here is undefined. You can define it in the controller or use Devise's current_user helper.

    Replacing:

    @user.avatar.url(:thumb)
    

    with:

    current_user.avatar.url(:thumb)
    

    should get you past this error as long as a user is signed in when seeing this view. Otherwise you'll need to check for nil before calling #avatar.