| 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.
|
||
Showing messages 1 through 2 of 2.
-
"Showing recipes in a category" code
2005-03-08 08:19:40 jfister [View]
-
"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



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.