views:

101

answers:

2

Can anyone tell me what's wrong with this code?

class Dataset < ActiveRecord::Base
  has_many  :dataitems  

def self.get_hash(dataset_id) 
  @dataitems = Dataset.find_by_id(24).dataitems
  @dataitems.each do |di|
    dataset_hash[di.axis0value] = di.axis1value #assign value for each category value
  end
  return dataset_hash
end

When run in dev environment it gives the following error in development.log:

rocessing BleeController#refresh_my_graph (for
127.0.0.1 at 2009-05-07 21:58:54) [GET]   Session ID: 8179153011071621ae181e852b03fbe1   Parameters: {"dataset_id"=>"24", "action"=>"refresh_my_graph", "controller"=>"blee"}   [4;36;1mDataset Columns (0.005285)[0m   [0;1mSHOW FIELDS FROM datasets[0m   [4;35;1mDataset Load (0.001132)[0m   [0mSELECT * FROM datasets WHERE (datasets.`id` = 24) LIMIT 1[0m   [4;36;1mDataitem Load (0.000646)[0m   [0;1mSELECT * FROM dataitems WHERE (dataitems.dataset_id = 24) [0m


NameError (undefined local variable or method `dataset_hash' for Dataset:Class):
    /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/gems/activerecord-1.15.3/lib/active_record/base.rb:1235:in `method_missing'
    /app/models/dataset.rb:12:in `get_hash'

The funny thing is, it works exactly as it should when run through the console. Any help greatly appreciated.

+1  A: 

Looks like you need to define the dataset_hash in your method. Something like this:

def self.get_hash(dataset_id)
  dataset_hash = {}
  @dataitems = Dataset.find_by_id(24).dataitems
  @dataitems.each do |di|
    dataset_hash[di.axis0value] = di.axis1value #assign value for each category value
  end
  return dataset_hash
end
Michael Sepcot
A: 

Or you can just 'inject':

def self.get_hash(dataset_id)
  Dataset.find_by_id(dataset_id).dataitems.inject({}) do |dataset_hash,di|
    dataset_hash.merge(di.axis0value => di.axis1value)
  end
end
Fer