Why is this ActiveRecord method raising the NameError?
Can anyone tell me what is 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 throws 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 that it works exactly the same as when launched through the console. Any help was much appreciated.
+1
Will
a source
to share
2 answers
It looks like you need to define dataset_hash
in your method. Something like that:
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
+2
a source to share