Women in Technology

Hear us Roar



Article:
  Rolling with Ruby on Rails, Part 2
Subject:   "Showing recipes in a category" code
Date:   2005-03-04 15:09:19
From:   petercooper
I'm sorry, but the "Showing recipes in a category" code here is not ideal, and certainly not the best/proper way to do what you're trying to do. Consider if you have 2000 recipes in your database, and the category you are trying to view only has one recipe. You've just loaded 2000 recipes into memory to only show 1! What's more, that sort of logic should not be in the view.


Something along the lines of:


@recipes = Category.find(@params['category']?).recipes


will get all the recipes for a specific category, and you won't need any logic in the view to deal with it.

Main Topics Oldest First

Showing messages 1 through 2 of 2.

  • "Showing recipes in a category" code
    2005-03-08 08:19:40  jfister [View]

    I have to agree 100%. It's easy with an application like Rails for beginning programmers to wreak havoc on a server by not being careful with their database queries. Unfortunately, this tutorial does just that in the "Showing recipes in a category" code.

    The working 'list' method of the Recipe controller should look like this:

    def list
    @category = @params['category']
    @recipes=Recipe.find_all("category_id="+@category)
    end

    As pointed out by petercooper, this allows the database server to weed out all records that do not match, rather than loading them all into memory so that the view can filter them.
  • "Showing recipes in a category" code
    2005-03-04 16:56:48  petercooper [View]

    Not sure why there's a ? in there, as I copy and pasted from something I said on IRC :-) But anyway it should be something like:

    @recipes = Category.find(@params['category']?).recipes