Why am I getting an undefined method `each' for nil:NilClass?

124 Views Asked by At

Total neophyte here. I'm just trying to list all of the objects in 'sites'. I know it's something agonizingly simple, but I just can't seem to track it down!

The error:

NoMethodError in Home#index

Showing /Users/jasonmurphy/data/projects/moviefeed/app/views/home/index.html.erb where     line #6 raised:

undefined method `each' for nil:NilClass
Extracted source (around line #6):

3: <u>SITES</u>
4: <br>
5: 
6: <% @sites.each do |site| %>
7:  <%= site.name %>
8:  <% end %>

My 'sites' controller:

class SitesController < ApplicationController
def index
    @sites = Site.all
end

def show
    @site=Site.find(params[:id])
end 
end

My view - Views/home/index.html.erb

<u>SITES</u>
<br>

<% @sites.each do |site| %>
<%= site.name %>
 <% end %>

And my routes.rb

resources :sites
resources :critics
root :to => "home#index"
1

There are 1 best solutions below

1
On

Without knowing any other information - it looks like it is never hitting your sites controller. I would change your root line to this:

root :to => 'sites#index'

You would then have to move your view code to your app/view/sites/ directory. Or alternatively you can move your controller code to your home controller.