Rails, nil object error

I have Categories controller and in layout _menu.html.erb I want to output all categories in home page but I have this error message:

You have a nil object when you didn't expect it! You might have expected an instance of Array. The error occurred while evaluating nil.each

When I logged as a administrator I can add, edit, delete and view all categories.

This is part of my code:

_menu.html.erb

<div class="menu"> <% @categories.each do |category| %> <li> <%= link_to category.title, category %> </li> <% end %> </div>

Categories_controller.rb

def index @title = "All categories" @categories = Category.paginate(:page => params[:page]) end def show @category = Category.find(params[:id]) @title = @category.title end def new @category = Category.new @title = "Add category" end def create @category = Category.new(params[:category]) if @category.save flash[:success] = "Successfully added category" redirect_to categories_path else @title = "Sign up" render 'new' end end def edit @category = Category.find(params[:id]) @title = "Edit category" end def update @category = Category.find(params[:id]) if @category.update_attributes(params[:category]) flash[:success] = "Category updated." redirect_to categories_path else @title = "Edit user" render 'edit' end end def destroy Category.find(params[:id]).destroy flash[:success] = "User destroyed." redirect_to categories_path end

end

-------------Problems Reply------------

@categories are defined only in the index action. I'm assuming you are using the _menu.html.erb as a partial in the layout - on every page.

The @categories will be nil for the others which will cause the exception.

There are basically two ways to define categories for all actions. One would be to do the call in the partial like

<% Category.all.each do |category| %>

The other way using a before filter in your controller

class CategoriesController
before_filter :load_categories

...

private

def load_categories
@categories = Category.all
end
end

I personally prefer the second way because I don't like database calls triggered in views.

Category:ruby on rails Views:0 Time:2012-03-01

Related post

  • Rails: HTML e-mail containing reference to a S3 hosted image handled by attachment_fu results in nil object error 2009-12-08

    I'm attempting to send out an HTML e-mail containing a photo (handled by attachment_fu) hosted on Amazon S3 following the submission of an entry. I keep receiving a nil object error when I try referencing the photo of an entry in ActionMailer. Here's

  • Infamous Nil Object Error w/ OmniAuth 2011-06-28

    You can see this error on SO: Nil object error when using OmniAuth (which normally works) OmniAuth / Rails - You have a nil object when you didn't expect it I have the same issue with my OmniAuth strategy. I've written my own, and have tested it both

  • Associated objects not accessible in views in Rails? nil object error 2009-07-22

    I have a 1:1 has_one / belongs_to relationship between users and registrations. One user has one registration. When I try to iterate through users in a view and display their registration info (source to follow), I get the following error: ActionView

  • Rails 3 nil object error on .each loop 2011-08-12

    I have the following code in a rake task, and I keep running into the error "You have a nil object when you didn't expect it" around the point the loop starts to run. I'm just going round and round on this. What have I done wrong on this loop? task :

  • Delayed_job in rails raising 'nil object' error 2012-04-05

    I'm struggling to use Delayed_job (collective idea v2.0 in a Rails 2.3.8 app). I'm calling the job from an application_controller method: ... Delayed::Job.enqueue(S3MoverJob.new(docs)) Where docs is a Hash with ids and names of files. At my Lib direc

  • nil object error when a form in a partial is submitted 2010-12-29

    Rails 2.3.5 I have a problem where a form select is working properly except when the form is submitted I get a nil error against the array being used. I'm not understanding how the Select tag is working and generating the correct HTML but also giving

  • How do I fix an unexpected nil object error? 2011-04-22

    I have this error when I try to add a comment via AJAX: ActionView::Template::Error (You have a nil object when you didn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.to_key): 1: $("#

  • Why am I getting a No Method and Nil Object error in the following line of codes? 2011-08-23

    I am trying to implement the following code in index.html.erb on rails and the following error appears on the server: NoMethodError in Users#index You have a nil object when you didn't expect it! You might have expected an instance of Array. The erro

  • ruby on rails nil.to_sym error 2009-11-10

    I'm not even sure how this broke. And I don't really know what the error means either. It was working previously. You have a nil object when you didn't expect it! The error occurred while evaluating nil.to_sym Extracted source (around line #3): 1:

  • Nil object error when using OmniAuth (which normally works) 2010-12-06

    I am having a weird error when using Omniauth. This appears to have little to do with my code. Is this the result of Twitter returning some weird deformed object? You have a nil object when you didn't expect it! You might have expected an instance of

  • Am i creating a nil object? (undefined method ___ for nil:NilClass) error - ruby on rails 2010-10-04

    My validations were working for a while, or so I thought. Now I come back to them after a while doing something else and I am getting the error above. I think it means I am creating a nil object with the .new method but I am just lost. It seemed to b

  • rspec error: Learn Rails by Example: You have a nil object when you didn't expect it 2011-12-09

    I am receiving an odd rspec error when walking through the Learn Rails by Example tutorial by Mike Hartl. On page 419, Listing 10.30: The code is as follows: it "should have an element for each user" do get :index @users[0..2].each do |user| response

  • Rails: nil error where I am sure the object is not nil 2011-08-02

    This method increments the ActiveRecord attr_accessible attribute current_step: def next_step logger.debug "Now at step: " + current_step.inspect if (current_step == nil) current_step = 0 end current_step = current_step + 1 end At execution of the me

  • Getting invalid Nil Object Exception when creating RSS feed in Rails 2010-06-20

    I'm creating an RSS feed for user notifications, each user has a feed unique to them which they get from a unique URL. The problem is that @notifications (set in the controller) is giving said to be a nil object, but @notifications both exists and co

  • OmniAuth / Rails - You have a nil object when you didn't expect it 2011-01-16

    I'm getting the following error in my Rails application and I have no idea how to go about debugging or fixing it: NoMethodError in AuthenticationsController#create You have a nil object when you didn't expect it! You might have expected an instance

  • Getting random nil.each error in mysql2 gem when using :include in Rails's find 2011-03-10

    I'm randomly (as it seems) getting a nil.each error on my localhost. Was feeling pretty confident in the code though so I pushed it to heroku and it works fine there. Here's my view code: <h2><%[email protected]%></h2> <br />

  • Ruby on Rails: Session Object Returning Nil 2011-06-30

    For some reason when I try to access the session object it seems to be returning nil. This happens mainly in ApplicationController but has also occurred in other controllers too. "You have a nil object when you didn't expect it! You might have expect

  • Rails - instance variable nil object in view 2011-12-01

    I'm working with some basic Rails scaffolding and know that instance variables are often used in the view to display data passed from a controller. In my app, there's a few sample users in the database (which I can pull up in console using results =

  • Rails, STI and 'becomes' - f.object.errors not showing in view 2011-12-08

    My question is: why doesn't .becomes pass errors over to the new object? Isn't this the expected behaviour? I have the following single table inheritance classes in a rails app: class Document < ActiveRecord::Base validates :title, :presence =>

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.086 (s). 11 q(s)