为什么这个ActiveRecord方法会引发NameError?

时间:2009-05-07 21:04:31

标签: ruby-on-rails ruby

有谁能告诉我这段代码有什么问题?

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

在dev环境中运行时,它在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'

有趣的是,它在通过控制台运行时完全正常。非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

您似乎需要在方法中定义dataset_hash。像这样:

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

答案 1 :(得分:0)

或者你可以'注射':

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