crcerror
crcerror

Reputation: 119

Rails undefined method `id' for nil:NilClass

I'm earning rails with the guidebook, but some code does not run as expected (use Rails 4.2.6, but book was written about older version). Appreciate if you can help me.

When i load pages of any of my objects (Ads) - i see nice page with object parameters, but when I load page with list of objects - I get

NoMethodError in Ads#index
Showing /home/mei33/mebay/app/views/ads/index.html.erb where line #11 raised:
undefined method `id' for nil:NilClass

<ul>
    <% for ad in @ads %>
        <li><a href="/ads/<%= @ad.id %>"><%= @ad.name %></a></li>
    <% end %>
</ul>

my ads_controler.rb looks like that:

class AdsController < ApplicationController
    def show
        @ad = Ad.find(params[:id])
    end

    def index
        @ads = Ad.all
    end
end

tried to add this line of code, but not helped:

def new
 @ad = Ad.new
end

maybe there is something I cannot notice? some mistake?

Upvotes: 0

Views: 1857

Answers (1)

oj5th
oj5th

Reputation: 1399

You should call as ad.id not @ad.id:

<ul>
    <% for ad in @ads %>
        <li><a href="/ads/<%= ad.id %>"><%= ad.name %></a></li>
    <% end %>
</ul>

Or:

<ul>
    <% @ads.each do |ad| %>
        <li><a href="/ads/<%= ad.id %>"><%= ad.name %></a></li>
    <% end %>
</ul>

Upvotes: 2

Related Questions