简体   繁体   中英

undefined method `each' for nil:NilClass

I am creating a rails app using ERB as my templating and keep getting this error: undefined method 'each' for nil:NilClass .

My event.html.erb looks like:

        <% @event.each do |event| %>
            <a href="/registrations/new?level_id=1" class="btn"><%= event.date.strftime("%B %d %Y") %></a>
            <br /><br />
        <% end %>

My register_controller.rb looks like this:

class RegisterController < ApplicationController
    def index
        @event = Event.all
    end 
end

def event
    @event = Event.find_by id: params["id"]
end 

My event.rb model:

class Event < ActiveRecord::Base
end

My route is this: get 'register/event/:id' => 'register#event'

When I go to /register/event/1/ I receive the error message undefined method 'each' for nil:NilClass . Any help would be greatly appreciated.

在此处输入图片说明

Thanks!

You are trying to iterate on a single object. Your event.html.erb file should simply look like:

   <a href="/registrations/new?level_id=1" class="btn">
     <%= @event.date.strftime("%B %d %Y") %>
   </a>

Also, it looks like that there is no object in the DB with your specified params[:id]

Also your controller, should look like this:

class RegisterController < ApplicationController
    def index
        @event = Event.all
    end 

    def event
       @event = Event.find_by id: params[:id]
    end
end

Looks like you're asking it to iterate over a single instance.

could go with:

<a href="/registrations/new?level_id=1" class="btn">
  <%= @event.date.strftime("%B %d %Y") if @event %>
</a>
<br /><br />

in event.html.erb

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM