【问题标题】:Undefined Method in Rails even though the method existRails 中未定义的方法,即使该方法存在
【发布时间】:2015-11-30 23:56:37
【问题描述】:

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

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

【问题讨论】:

  • 正如您在问题中已经说过的,助手是为了查看。为了在你的模型中使用它see this questionor this tutorial
  • 简答:在模型中使用视图助手。视图助手用于视图。看起来您只需要一个简单的实用程序库/类/模块。
  • 这些 cmets 让我朝着正确的方向前进。我决定将该方法移至模型并使其成为类级别的方法。现在一切正常

标签: ruby-on-rails ruby activerecord


【解决方案1】:

您已经定义了一个不需要实例化的模块。您应该可以在没有 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

但是您不应该为此使用帮助程序,您可以创建一个普通模块并以相同的方式要求它。

编辑:将模块保存在名为 app/modules 的新文件夹中(并重新启动服务器),将模块内容保存在名为 stb_helper.rb 的文件中:

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

【讨论】:

  • 是的,和模块一样,对吧?这样做的唯一惩罚是视图中不必要的可用性。
猜你喜欢
  • 2021-10-13
  • 2019-04-28
  • 2011-11-17
  • 1970-01-01
  • 1970-01-01
  • 2016-06-13
  • 2017-05-30
  • 2011-06-16
  • 1970-01-01
相关资源
最近更新 更多