Teresa
Teresa

Reputation: 373

undefined method `each' for nil:NilClass - but only when rendering on homepage

I have a model Person and I want to list all 'people' on the home page of my website.

I created a partial _index.html.erb for this, so I could use this list everywhere on my website. On index.html.erb, I render this partial.

Now both http://localhost:3000/people/ and http://localhost:3000/people/index run fine. However, I also wanted to use the index partial on my home page. There, it gives the following error:

undefined method `each' for nil:NilClass

Some parts of my code:

people/_index.html.erb

<h2>The following people exist:</h2>
<table>
  <tr>
    <th>Name</th>
  </tr>
  <% @people.each do |p| %>
      <tr>
        <td><%= p.name %></td>
      </tr>
  <% end %>
</table>

people/index.html.erb

<%= render 'people/index' %>

pages/index.html.erb (This is my home page)

<h1>Homepage</h1>

<%= render 'people/new' %>
<%= render 'people/index' %>

routes.rb:

Rails.application.routes.draw do
  root 'pages#index'
  get 'pages/index'
  get 'people/index'
  resources :people
end

Part of people_controller.rb:

class PeopleController < ApplicationController

  def index
    @people = Person.all
  end

  def show
    @person = Person.find(person_params)
  end

...

Somehow, rendering people/new (also a partial) works perfectly fine if I comment out <%= render 'people/index' %>.

Searching for this error leads mainly to the solution "you didn't properly define @people in the controller". However, why does it then work fine on the /people/index page but not when rendering it on the homepage? Is it a routing issue?

I hope that my question is clear and that I posted enough code snippets, thanks in advance for your help!

Upvotes: 0

Views: 1874

Answers (2)

mauro_oto
mauro_oto

Reputation: 1378

Your PagesController, which is called when you hit the pages/index route when rendering the homepage, doesn't have @people defined, so @people ends up being nil, and the error occurs.

You need to add @people = People.all somewhere in your PagesController, since PeopleController doesn't actually get called when you access the homepage.

If you check your development.log you will see PeopleController does not get called when you access the homepage and the people/_index partial renders.

Upvotes: 2

aspencer8111
aspencer8111

Reputation: 786

undefined method 'each' for nil:NilClass means that you are calling each on something you think is there, but isn't. In this case your calling @people.each, but @people is actually nil. So you see that error. In your controller set @people = People.all in the action/method that is actually fueling that page. So if you are on the show page, it would go in the show method. On the edit page, makes sure that code is in the edit method.

Upvotes: 0

Related Questions