Chad
Chad

Reputation: 31

a simple rails 3.1 view using group_by

I have a menu on a site I am working on, menu of food_items. Each of the records in the table also contains a field of category. This category can be burgers, munchies, drinks, or anything else they want to categorize food items by.

I am trying to display the menu, with items grouped by this category field. My attempt so far:

food_item_menus_controller.rb
...
def food_list
  @foods = FoodItem.all
  @food_list = @foods.group_by { |t| t.category }
end


views/food_item_menus/index.html.haml
= @food_list.group_by (@food_items.category).each do |food_list|
  %p
    = food_list.name
  %ul
    -  for food_items in food_items
      %li
        = food_items.name

My error is that I have a nil object. I guess my call to @foods isn't returning anything.

models/food_item.rb
class FoodItem < ActiveRecord::Base
  has_many :menus, :through => :food_item_menus
  has_many :food_item_menus
end

Did I set up something wrong? Or is my thinking wrong that if I call @foods in the view, it's not actually calling the variable I set in the controller? The more I try to figure this out, the more I am just getting confused about everything, including the basics.

Upvotes: 3

Views: 1519

Answers (2)

WattsInABox
WattsInABox

Reputation: 4636

You should use a scope on the model, instead.

class FoodItem
    scope :categorized, -> { group(:category) }
end

references http://guides.rubyonrails.org/active_record_querying.html#group http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html

Upvotes: 0

Tobias Cohen
Tobias Cohen

Reputation: 20000

Your view code is full of errors, it should be something like this:

= @food_list.each do |category, food_items|
  %p
    = category
  %ul
    - food_items.each do |food|
      %li
        = food.name

Breakdown of errors:

  • @food_list.group_by(@food_items.category).each do |food_list| - you haven't assigned a value to @food_items anywhere; @food_list is assigned as the result from a group_by call in your controller, so here you're calling it twice; group_by returns a hash, so your each block should have two arguments, not one.
  • for food_items in food_items - using the same variable name for the iterated variable and the iterator; food_items is not assigned a value anywhere.

Upvotes: 2

Related Questions