Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

undefined method `first_name' for nil:NilClass rails 4+

l am getting this error:

Showing /Users/kelvinatawura/sites/socil-media/app/views/statuses/show.html.erb where line #5 raised:

undefined method `first_name' for nil:NilClass

while doing the treehouse app any idea how l can resolve it? For some reason the code

 <%= @status.user.first_name %>

seem to be causing the issue.

Jason Seifer Jim Hoskins

9 Answers

Vlad Filiucov
Vlad Filiucov
10,665 Points

it may be database problems. Found same problem on the forum

Try to go to rails console, type in "u = User.first" to see the ID of this user, log in with this user and when you create the status, type in the ID of this user.

thanks, its now returning no erros however not displaying the name of the user. with <%= @status.user.full_name %> . any thoughts on that?

Vlad Filiucov
Vlad Filiucov
10,665 Points

it has something to do with the course. You where trying to access status of a deleted user, or tried deleted status. Think i had ran into the same error year ago. It seems to me that i solve it with dropping database and then seeding and migrating it again. But i'm not sure now. Anyway nill:class error shows us that we are trying to run a method on an object that dosen't exists.

Vlad Filiucov
Vlad Filiucov
10,665 Points

check syntax in db/migrate/20150000_devise_create_user you may have a typo in first_name there

class DeviseCreateUsers < ActiveRecord::Migration
  def change
    create_table(:users) do |t|
      t.string :first_name
      t.string :last_name
      t.string :profile_name
      ## Database authenticatable
      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      t.integer  :sign_in_count, default: 0, null: false
      t.datetime :current_sign_in_at
      t.datetime :last_sign_in_at
      t.string   :current_sign_in_ip
      t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :users, :email,                unique: true
    add_index :users, :reset_password_token, unique: true
    # add_index :users, :confirmation_token,   unique: true
    # add_index :users, :unlock_token,         unique: true
  end
end

it looks totally fine

Vlad Filiucov
Vlad Filiucov
10,665 Points

what about application_controller? app/controllers/application_controller

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception

end

l didn't add any attr_accessible stuff because they kept returning me errors.

Vlad Filiucov
Vlad Filiucov
10,665 Points

there is no attr_accessible in rails 4 ...they are now using strong parameters instead. This course is out of date

Vlad Filiucov
Vlad Filiucov
10,665 Points

can you show me your status controller?

class StatusesController < ApplicationController
  before_action :set_status, only: [:show, :edit, :update, :destroy]

  # GET /statuses
  # GET /statuses.json
  def index
    @statuses = Status.all
  end

  # GET /statuses/1
  # GET /statuses/1.json
  def show
  end

  # GET /statuses/new
  def new
    @status = Status.new
  end

  # GET /statuses/1/edit
  def edit
  end


  # POST /statuses
  # POST /statuses.json
  def create
    @status = Status.new(status_params)

    respond_to do |format|
      if @status.save
        format.html { redirect_to @status, notice: 'Status was successfully created.' }
        format.json { render :show, status: :created, location: @status }
      else
        format.html { render :new }
        format.json { render json: @status.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /statuses/1
  # PATCH/PUT /statuses/1.json
  def update
    respond_to do |format|
      if @status.update(status_params)
        format.html { redirect_to @status, notice: 'Status was successfully updated.' }
        format.json { render :show, status: :ok, location: @status }
      else
        format.html { render :edit }
        format.json { render json: @status.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /statuses/1
  # DELETE /statuses/1.json
  def destroy
    @status.destroy
    respond_to do |format|
      format.html { redirect_to statuses_url, notice: 'Status was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_status
      @status = Status.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def status_params
      params.require(:status).permit(:name, :content, :user_id)
    end
end

ohh right no wonder. l was really struggling.

Vlad Filiucov
Vlad Filiucov
10,665 Points

yp we had for nil:NilClass error. That means that @status.user. is nill update your show and edit methods

how would that look like please?

Vlad Filiucov
Vlad Filiucov
10,665 Points

def show @status = Status.find(params[:id])

end

def edit @status = Status.find(params[:id]) end

still gives the error any ideas?

Vlad Filiucov
Vlad Filiucov
10,665 Points

i would also try doing rake db:drop than rake db:migrate

You're not assigning the user to the status,

# add the before_action :authenticate_user! line, like this

before_action  :set_status, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!

then

def new
    @status = current_user.statuses.build(status_params)
end

and

def create
    @status = current_user.statuses.build(status_params)
    # keep all the other code that is under this line
end

Instead of

     <%= @status.user.first_name %>

you could do this

    <%= current_user.first_name %>

I hope this helps :)