Rolling with Ruby on Rails, Part 2
Subject:   "Showing recipes in a category" code
Date:   2005-04-05 12:45:39
From:   co_banzai
Response to: "Showing recipes in a category" code

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

Full Threads Oldest First

Showing messages 1 through 1 of 1.

  • "Showing recipes in a category" code
    2005-04-22 03:38:42  xeal [View]

    I also think that using the field is better - after all the might not be unique.

    And the code simplifies, so you can write the whole RecipeController.list method as:

    def list
    @recipes = Recipe.find_all(@params["category_id"] ? ("category_id = " + @params["category_id"]) : nil)

    The code above passes to Recipe.find_all a category_id, if @params["category_id"] is not empty or nil otherwise.

    Of course, the statement from list.rhtml that renders the category needs to be changed as:

    <td><%= link_to, :action => "list", :category_id => %></td>