Women in Technology

Hear us Roar



Article:
  Rolling with Ruby on Rails, Part 2
Subject:   Better way of filtering Recipes by Category
Date:   2005-04-07 20:06:05
From:   Rexbot
Instead of having all that nasty code in the html try just defining controler as follows:


def list
@category = @params['category']
@recipes_tmp = Recipe.find_all
@recipes = []
@recipes_tmp.each{|recipe|
if (@category == nil) ||
(@category == recipe.category.name)
@recipes << recipe
end
}
end


I think this better shows the elegance of having a MVC framework like Rails.


Better yet to let the DB do the work in the Recipe.find query and/or add a new method to the Recipe model for this behaviour but this gets the point across...

Full Threads Newest First

Showing messages 1 through 3 of 3.

  • Curt Hibbs photo Better way of filtering Recipes by Category
    2005-04-07 20:18:11  Curt Hibbs | O'Reilly AuthorO'Reilly Blogger [View]

    I completely agree that the best way to do this through the proper database queries within a method in the Recipe model.

    Obviously, this article was not about best practices. :-)
    • Better way of filtering Recipes by Category
      2005-05-22 12:34:49  lewinke [View]

      I'm not sure that this is any better but here is what I ended up with:

      Adding this method to RecipeController

      def list_category
      @recipes = Recipe.find_all_by_category_id(@params['id'])
      render_action "list"
      end


      And changing list.rhtml to make the category a link


      <td><%= link_to recipe.category.name, :action => "list_category", :id => recipe.category.id %></td>


      This could be HUGELY wrong since I've only spent about 45 minutes with rails and no time with ruby before that.
    • Better way of filtering Recipes by Category
      2006-08-08 11:04:07  Steogede [View]

      Just like to say I thought the article was great. I also picked up that the view was not necessarily the best place to filter the categories and also that the category.id was probably a better attribute to search on.

      However, like you said the article was not about best practices. It gave me the chance to think on my own and see if I had learn't enough to write some of my own code. To my complete (albeit undeserved) surprise, I had picked up enough from your two tutorials (and a quick glance at the API docs) to make the changes I felt necessary.