Reputation: 29
I receive an undefined method error on `each' for nil:NilClass.
The template:
<th>name></th>
<th>Comment</th>
<% @guests.each do |guest| %>
<tr>
<td><%= guest.name %></td>
<td><%= guest.comment %></td>
</tr>
<% end %>
The controller:
class GuestsController < ApplicationController
def index
@guest = Guest.all
end
def show
@guest = Guest.find(params[:id])
end
def new
end
def create
@guest = Guest.new(article_params)
@guest.save
redirect_to @guest
end
private
def article_params
params.require(:guest).permit(:name, :email, :doctor, :Captain, :comment )
end
end
Upvotes: 0
Views: 738
Reputation: 7405
undefined method `each' for nil:NilClass
This is error stating that, you are trying to use the each
method of a nil
object, that is you do not have anything defined as @guests
in your index
action.
You are actually trying to access the instance variable @guest
of index action in your view.
So you need to fix the typo:
<% @guest.each do |guest| %> # you wrote @guests
Suggestion: Since you are fetching all the guests, you should change your instance variable name from @guest to @guests to be more appropriate. In that case you do not have to change your view code. It will work as it is.
def index
@guests = Guest.all
end
Upvotes: 0
Reputation: 1191
change your code is like this:
def index
@guests = Guest.all
end
You are using @guests at view but in controller it is @guest
Upvotes: 0
Reputation: 6100
You nowhere have @guests
, in all of your methods you have @guest
. This is why @guests
has nill value, you have not define it.
Upvotes: 0
Reputation: 1705
In your index
method you are using @guest = Guest.all
and in your view file, you have specified <% @guests.each do |guest| %>
. So you should change @guests
to @guest
in your view file.
Change this,
<% @guest.each do |guest| %>
in your view file
Upvotes: 0
Reputation: 31477
You have a typo in your #index
method, replace @guest
with @guests
.
Like:
def index
@guests = Guest.all
end
Upvotes: 3