2015-11-30 39 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

是的,與模塊相同的東西嗎?只有這樣處罰,纔會是視圖中不必要的可用性。 –