Reputation: 77
Can anyone tell me what I am doing wrong?
This is my views/application.html.erb
<div class="table">
<h1 align="center"><p class ="navbar-fouls" style="color:#48A5E3" >Recent Fouls</p></h1>
<table align="center" style="width:100%">
<tr>
<% if Foul.any? %>
<%= @foul.law %>
<% else %>
<p class="text-center" style="center">Game has not started yet.</p>
<% end %>
</tr>
</table>
I am getting the error
undefined method `law' for nil:NilClass
Extracted source (around line #79):
76 <table align="center" style="width:100%">
77 <tr>
78 <% if Foul.any? %>
79 <%= @foul.law %>
80 <% else %>
81 <p class="text-center" style="center">Game has not started yet.</p>
82 <% end %>
I have this in my foul controller I do not understand why it is giving me this error when @foul is clearly defined.
class FoulsController < ApplicationController
before_action :authenticate_user!
def index
@fouls = Foul.all
end
def show
@foul = Foul.find(params[:id])
end
def new
@foul = Foul.new
end
def create
@foul = Foul.new(fouls_params)
if @foul.save
redirect_to(:action => "index")
else
render("new")
end
end
def edit
@foul = Foul.find(params[:id])
end
def update
@foul = Foul.find(params[:id])
if @foul.update_attributes(fouls_params)
redirect_to(:action => "show", :id => @foul.id)
else
render("index")
end
end
def destroy
foul = Foul.find(params[:id]).destroy
redirect_to(:action => "index")
end
private
def fouls_params
params.require(:foul).permit(:law, :description)
end
end`
Upvotes: 0
Views: 237
Reputation: 8586
Instead of checking for Foul.any?
in views/application.html.erb
you should probably check for if @foul
Foul.any?
makes a call to your database, but if @foul
checks what the variable is actually set to.
<% if @foul %>
<%= @foul.law %>
<% else %>
<p class="text-center" style="center">Game has not started yet.</p>
<% end %>
Upvotes: 0
Reputation: 1121
It's expecting your controller to supply an @foul
instance variable. Here, the controller set @foul = nil
(unless it's index
and @foul
isn't getting set at all).
Upvotes: 2