0
votes

I can’t wrap my head around this and I could use some fresh eyes. I’m getting an undefined method in one of my views and I can’t figure out why.

I have a group of controllers under an admin namespace (i.e admin/restaurants, admin/menu). I also have a controller for admin but no model backing it. I want to use the admin index page as a dashboard to display various data from the other controllers namespaced under it. For some reason when I try to access any data from the other controllers in the admin/index view I get undefined method `each' for nil:NilClass

Routes

namespace :admin do
   resources :restaurants
   resources :menus
end

Controller in app/controllers/admin_controller.rb

class AdminController < ApplicationController

def Index
     @restaurants = Restaurant.all
     @menus = Menu.all
end

Views in app/views/admin/index.html.erb

<% @restaurants.each do |restaurant| %>
    <%=  restaurant.name   %>
    <%=  restaurant.address   %>
<% end %>

<% @menus.each do |menu| %>
    <%=  menu.name   %>
    <%=  menu.price   %>
<% end %>
2
Hi @Ria, you've posted a number of questions that have several upvotes each, but you haven't accepted any of them. Please remember that in the SO community, it's considered both polite and helpful to accept answers that have best address your question: meta.stackexchange.com/questions/5234/… - zeantsoi
Sorry for the typos. I type them from my code instead of copying and pasting. I'll make the spelling changes. However, I still get undefined method for each on the @restaurants. The interesting part is that I used the same exact code on other pages, such as the home page that is also has a controller but no model and it works perfectly, which is why I thought it had something to do with the namespace. - Ria
It appears that you've updated with some typo corrections, but can you please verify whether the casing for the action definition within your controller is def index, and not def Index? - zeantsoi
I did have Index instead of index. Such a knuckle headed move on my part, but thank you for helping me out. Thanks for the info about accepting answers too. - Ria

2 Answers

0
votes
@menus = Menu.all

in controller, plural

@menu.each do |menu| %>

in view, single.

@menu is undefined, and it is nil.

0
votes

This probably isn't related to the namespace. Rather, you have some crucial typos that will need to be resolved (namely, incorrect casing in your controller and mis-named @menus object in your view).

Try the following:

# app/controllers/admin_controller.rb
class AdminController < ApplicationController

def index
    @restaurants = Restaurant.all
    @menus = Menu.all
end

# app/views/admin/index.html.erb
<% @menus.each do |menu| %>
    <%=  menu.name   %>
    <%=  menu.price   %>
<% end %>

Also, you'll need to ensure that your admin controller has a route (and not just a namespace):

resources :admin, :only => :index # You've probably already done this if you're receiving a view error