Rolling with Ruby on Rails, Part 2
Subject:   "Showing recipes in a category" code
Date:   2005-03-11 15:46:16
From:   automat_svet
Response to: "Showing recipes in a category" code

I get this error: undefined method `each' for nil:NilClass
sure I'm doing something wrong in list.rhtml :-(

any suggestion?

Main Topics Oldest First

Showing messages 1 through 2 of 2.

  • "Showing recipes in a category" code
    2005-04-05 12:45:39  co_banzai [View]

    Yeah, I got the same error. I found that I had to make a couple changes to get this working.

    1) On the list.rhtml page, there is a line that reads:

    :category => "#{}" %>

    This results in it passing the categoty name in the category parameter, which is wrong; it needs to pass the category_id To make things clearer, I also altered the name of the parameter to reflect this change. After doing so, the above line of code was changed to:

    :category_id => "#{}" %>

    2) I had to update the list method of the recipe controller class in two ways. First, I had to put in a conditional clause so that when the category_id is not defined, it returns all of the data (I'm new to RoR, so there may be a better way to do this). Second, I had to use find_all_by_category_id instead of find_by_category_id. According to the docs, I shouldn't need to do this but I found that without this I got an error (I'm on Rails 0.11). When it was all said and done, my list method looked like so:

    def list
    @category_id = @params['category_id']
    if @category_id
    @recipes = Recipe.find_all_by_category_id(@category_id)
    @recipes = Recipe.find_all

    Hope that helps
  • Curt Hibbs photo "Showing recipes in a category" code
    2005-03-11 16:57:37  Curt Hibbs | O'Reilly AuthorO'Reilly Blogger [View]

    First of all, let me say that what I answered above about using @category_id is incorrect, the article is correct as written (I must have been on drugs when I wrote that :-).

    In you case, I'm assuming that you cut'n'paste the code for list.rhtml, so the line on which you are getting the error contains "@recipes.each", which is going to iterate through each member of the collection contained in @recipes.

    The error says the @recipes contains the value "nil" (the Ruby equivalent of Java's null), and that the object "nil" does not have a method named "each".

    That means that something is wrong in the controller where @recipes is being assigned its value. Make sure you list method looks like this:

    def list
    @category = @params['category']
    @recipes = Recipe.find_all

    If it already does, then that means that find_all is failing to find any recipes in the database (or failing to find the database).

    Did you go through part 1 successfully? Does your database contain some recipes?

    You could try starting off the my zip file for your code and use my sql file to initialize your database, and then start working through part 2.