In my index.html.erb
file, this lot of code works:
<% if Restaurant.all.any? %>
<% Restaurant.all.each do |restaurant| %>
<h2><%= restaurant.name %></h2>
<% end %>
<% else %>
<h1>No restaurants yet!</h1>
<% end %>
<a href='#'>Add a restaurant</a>
However, when I change the controller to this:
class RestaurantsController < ApplicationController
def index
@restaurants = Restaurant.all
end
end
and the index.html.erb
file to this:
<% if @restaurants.any? %>
<% @restaurants.each do |restaurant| %>
<h2><%= restaurant.name %></h2>
<% end %>
<% else %>
<h1>No restaurants yet!</h1>
<% end %>
<a href='#'>Add a restaurant</a>
all of the tests which passed, now fail because of that change, and I can't for the life of me work out why they are not working. The error message when running the tests is:
Failure/Error: visit '/restaurants'
ActionView::Template::Error:
undefined method `any?' for nil:NilClass
My routes.rb file is as follows:
Rails.application.routes.draw do
resources :restaurants
end
Actually the problem is that your index is called directly without going to controller. So earlier your "Restaurant.all"
works correctly but now atfer new changes @restuanants
is null and you applied null.any?
. It gives error. try
<% if @restaurants && @restaurants.any? %>
or
<% unless @restaurants.blank? %>
Try this I hope this will help
In index.html.erb
<% unless @restaurants.blank? %>
<% @restaurants.each do |restaurant| %>
<h2><%= restaurant.name %></h2>
<% end %>
<% else %>
<h1>No restaurants yet!</h1>
<% end %>
<a href='#'>Add a restaurant</a>
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.