2015-11-30 40 views
0

我有一个方法在我的视图助手目录,我试图在模型中使用,但我不断收到未定义的方法错误。我无法弄清楚我做错了什么。这是我的模块。在Rails中未定义的方法,即使方法存在

module StbHelper 
def gen_csv(stbs) 
    CSV.generate do |csv| 
     csv << [ 
      'param1', 
      'param2' 
     ] 
     stbs.each do |stb| 
      health_check = stb.stb_health_checks.last 
      csv << [ 
       'value1', 
       'value2' 
      ] 
     end 
    end 
end 

这是我想使用该方法的类。

require 'stb_helper' 
class Stb < ActiveRecord::Base 

    def self.get_notes_data 
     . 
     . 
     . 
    end 

    def self.update 
     . 
     . 
     . 
    end 

    def self.report(options={}) 
     csv_file = nil 
     if options == {} 
      ######################################## 
      # This is the line that throws the error 
      csv_file = StbHelper.gen_csv(Stb.all) 
      ####################################### 
     else 
      stbs = [] 
      customers = List.where(id: options[:list])[0].customers 
      customers.each do |customer| 
       customer.accounts.each do |account| 
        stbs += account.stbs 
       end 
      end 
      csv_file = StbHelper.gen_csv(stbs) 
     end 
    end 
end 
+1

您:保存模块中的名为app /模块的新文件夹(并重新启动服务器),保存了一个名为stb_helper.rb与模块的内容文件问题,助手是意见。为了在你的模型中使用它[见这个问题](http://stackoverflow.com/questions/489641/using-helpers-in-model-how-do-i-include-helper-dependencies),[或this教程](http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model) –

+1

简短回答:在模型中使用视图助手。查看助手是意见。看起来你只是想要一个简单的实用程序库/类/模块。 –

+0

这些评论有点让我指向正确的方向。我决定将该方法移至模型并使其成为类级别的方法。一切正常现在 –

回答

0

您已经定义了一个模块,不需要实例化。您应该能够使用它没有StbHelper部分(只要你需要在文档中的模块):

def self.report(options={}) 
    csv_file = nil 
    if options == {} 
     ######################################## 
     # This is the line that throws the error 
     csv_file = gen_csv(Stb.all) 
     ####################################### 
    else 
     stbs = [] 
     customers = List.where(id: options[:list])[0].customers 
     customers.each do |customer| 
      customer.accounts.each do |account| 
       stbs += account.stbs 
      end 
     end 
     csv_file = gen_csv(stbs) 
    end 
end 

但你不应该使用这个帮手,你可以创建一个正常的模块,需要它以同样的方式。

编辑:正如你已经说

module StbHelper 
def gen_csv(stbs) 
    CSV.generate do |csv| 
     csv << [ 
      'param1', 
      'param2' 
     ] 
     stbs.each do |stb| 
      health_check = stb.stb_health_checks.last 
      csv << [ 
       'value1', 
       'value2' 
      ] 
     end 
    end 
end 
+0

是的,与模块相同的东西吗?只有这样处罚,才会是视图中不必要的可用性。 –