Latest Rails ‘Gotcha’ Solved

March 1, 2008

So continuing my Ruby on Rails adventure it seems I have hit another problem. Luckily this one seems quite easy to fix, although it did take me a good old time to find the solution.

Maybe it’s also obvious to everyone else in the world and it was only me that was stuck, but maybe not. So I’m sharing this here to help others who might be interested.

The Situation

I have two models, Products and Categories. Products belong to a Category. So when searching for all the Products for a given category I have the following ruby code in my controller;

def show_category
  id = params[:id]
  @category = Category.find_by_id(id)
  @products = Product.find_by_category_id(id)
end

What I’m expecting is to return a list of Products to my view, all of which belong to a category.

The Problem

But instead I was getting the following error;

undefined method `each' for #

For this view code;

<% for product in @products %>

The Solution

I worked out that this is because for the data I was testing only one product was being returned from the find method. This was correct behaviour because there was only one product in the data. But that meant that a single Product object was being returned, not a Collection containing a single Product object. So change the controller to look like;
def show_category
  id = params[:id]
  @category = Category.find_by_id(id)
  @products = Product.find_all_by_category_id(id)
end

And a collection is always returned, even if there is only one Product. Problem solved.