Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

General Discussion

NoMethodError -Simple Rails App

I'm getting the following error when trying to set up the user id's in the Simple Web App series.

NoMethodError in Statuses#index

Showing /Users/TomEllis/Projects/treebook/app/views/statuses/index.html.erb where line #9 raised:

undefined method `user' for nil:NilClass

I'm assuming it's something to do with the user id not being associated with the status. The odd thing is, it works fine on the 'show' status page with single statuses but on the index.html page, or 'all statuses', I get the error.

How can it work on one, but not the other?

Heres's the 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
# attr_accessible :title, :body

has_many :statuses

def full_name
  first_name + " " + last_name


and here's the index.html.erb

<div class="page-header"> <h1>All of the Statuses</h1> </div>

<%= link_to "Post a New Status", new_status_path, class: "btn btn-success" %>

<% @statuses.each do |status| %>
<div class="status">
  <strong><%= @status.user.full_name %></strong>
  <p><%= status.content %></p>
  <div class="meta">
    <%= link_to time_ago_in_words(status.created_at) + " ago", status %>
    <span class="admin">
      | <%= link_to "Edit", edit_status_path(status) %> |
      <%= link_to "Delete", status, method: :delete, data: { confirm: "Are you sure you want to delete this status?"} %>

<% end %>

1 Answer

Ah I figured it out.

The erb for @status.user.full_name in the loop didn't need the leading '@', presumably because it had been passed in above.

All working!