Search code examples
ruby-on-railsrubymethodsstatus

undefined method `full_name' for nil:NilClass


This is an exercise on teamtreehouse.com.

user.rb

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,
                  :first_name, :last_name, :profile_name

  validates :first_name, presence: true

  validates :last_name, presence: true

  validates :profile_name, presence: true,
                           uniqueness: true

  has_many :statuses

  def full_name
    first_name + " " + last_name
  end
end

status.rb

class Status < ActiveRecord::Base
  attr_accessible :content, :user_id
  belongs_to :user
end

I'm getting the following error.

undefined method 'full_name' for nil:NilClass

Showing /app/views/statuses/index.html.erb where line #9 raised:

6: 
7: <% @statuses.each do |status| %>
8: <div class="status">
9:  <strong><%= status.user.full_name %></strong>
10:     <p><%= status.content %></p>
11:     <div class="meta">
12:       <%= link_to time_ago_in_words(status.created_at) + " ago", status %>

I would really like to understand why.


Solution

  • The issue was that when I was building the status portion prior to the user part, I had generated test statuses that didn't have a first_name or a last_name.

    The way to fix it was to open the rails console type: rails console then Status.delete_all