Search code examples
ruby-on-railsrubymethodspaperclipgrails-controller

Getting undefined method `builder_photo' for nil:NilClass error


I have a Builder profile image which is stored in Database table Builders.

I want to show the current_user image that is builder profile image in the navigation bar.

Sp I used.

<%= image_tag(@builder.builder_photo.url, class: 'builder-img') %>

This shows correct profile image in

  • http://localhost:3000/api/v1/builders/:id/edit

but on other pages it showing an error

undefined method `builder_photo' for nil:NilClass

I am new to rails. Please someone help me to solve this.


Solution

  • This is one of the most common error you can find in rails. Anytime you see this format: undefined method * builder_photo* for nil:NilClass, it means @builder is nil (and nil don't have the builder_photo method, of course). Where is this @builder variable defined?

    Normally you setting variable like this in the controller file, for example:

    class CarsController < BaseController
      def index
        @builder = Builder.new(a: 1, b: 2)
      end
    end