I used this code in my “users” views and had no trouble: <% if current_user.admin? %>. But using it in a set of views associated with a different controller throws up the “No method Error.”
Background: the app allows admins to create scavenger hunts. Admins should be able to delete hunts. I thought I knew how to configure everything, but apparently, I’m missing something. Here’s my code:
controller.rb
class HuntsController < ApplicationController
def index
@title = "All Hunts"
@hunts = Hunt.order("name ASC")
end
def show
@hunt = Hunt.find(params[:id])
@title = @hunt.name
end
def new
@hunt = Hunt.new
@title = "New Hunt"
end
def create
@hunt = Hunt.new(params[:hunt])
if @hunt.save
flash[:success] = "Hunt created!"
redirect_to hunts
else
@title = "New Hunt"
render 'new'
end
end
def edit
@hunt = Hunt.find(params[:id])
@title = "Edit hunt"
end
def delete
Hunt.find(params[:id]).destroy
flash[:success] = "Hunt destroyed."
redirect_to index
end
end
Views/Index.html.erb
<h1>All Hunts</h1>
<ul>
<% @hunts.each do |hunt| %>
<%= render hunt %>
<% end %>
</ul>
<%= link_to( "Create New Hunt", '/hunts/new') %>
Views/_hunt.html.erb
<li>
<%= link_to hunt.name, hunt %>
<% if current_user.admin? %>
<%= link_to "delete", hunt, :method => :delete, :confirm => "You sure?",
:title => "Delete #{hunt.name}" %>
<% end %>
</li>
Error Message when trying to head to /hunts:
NoMethodError in Hunts#index
Showing ...../app/views/hunts/_hunt.html.erb where line #3 raised:
undefined method `admin?' for nil:NilClass
current_userisnil, and thus does not know how to respond toadmin?. Either ensure thatcurrent_useris always a user instance, or check that it’s notnil.In Ruby 2.3+, one can use the “safe navigation” operator (
&.):In Ruby 2.2 and earlier, instead use boolean short-circuiting:
Note that ActiveSupport has
try, but that has different behavior which will potentially hide bugs. For similar behavior, usetry!instead.Getting “undefined method _____ for nil:NilClass” is a very common occurrence in Ruby, so get used to it happening often
:).