【问题标题】:How to call a model method in view helper?如何在视图助手中调用模型方法?
【发布时间】:2014-01-23 03:42:46
【问题描述】:

如何从视图助手中的模型调用类方法。基本上,该视图根据传递给操作的类型 ID 列表显示搜索结果。但是在视图而不是搜索 ID 上,我想显示这些产品的描述而不是 ID。

用户从视图上的选择框中选择产品 ID -> 控制器操作选择具有该产品 ID 的订单 -> 结果视图具有订单详细信息,但必须在屏幕顶部从查找表中显示产品描述其中有 id 和描述。 现在,当我尝试在辅助方法中访问产品描述时,我得到一个

未初始化的常量 DownloadHelper::MetaProductType 异常。

我知道我们可以在模型中调用辅助方法,但是如何在辅助中调用模型方法?

产品型号如下

class MetaProductType < ActiveRecord::Base

    def self.get_product_type_description type_list
            where('lower(product_type) in (?)', type_list).select('product_description')
    end

end

辅助方法是:

module DownloadHelper

    def print_hash(hash)

        return_str = ''
        return return_str if hash.nil?

        hash.each_pair do |key, value|
        key_arr = key.split('_')

        return_str = return_str + key_arr.join(' ').capitalize
        return_str = return_str + ' : ' 

        if key.downcase.include? 'product'

            #print product type descriptions
            arr = value.split(',')
            value = MetaProductType.get_product_type_description value

        end

        return_str = return_str + '<br />'
        return_str.gsub!(/\w+/){$&.capitalize}

    end

    return (return_str)

end

【问题讨论】:

  • 您好,请为助手和模型添加代码
  • 您好,请编辑问题,将您的代码放入问题中并按照堆栈溢出约定格式化(4 个空格缩进)
  • 你确定value = MetaProductType.get_product_type_description value正在被执行吗?它会抛出错误吗?
  • 这个助手是否位于助手目录中?
  • 当您尝试执行此操作时,请添加 Web 服务器控制台输出。

标签: ruby-on-rails ruby model helper


【解决方案1】:

本来打算写评论,但在这里会更容易:


语法

可能是错的,但我认为问题在于您的 passing of arguments 到您的类方法

为什么不试试这个:

#app/models/meta_product_type.rb
class MetaProductType < ActiveRecord::Base
    def self.get_product_type_description(type_list)
            where('lower(product_type) in (?)', type_list).select('product_description')
    end
end

#app/helpers/download_helper.rb
value = MetaProductType.get_product_type_description(value)

另一个问题可能是您在助手中自引用了value var?为什么不重命名它,以免使用相同的变量

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2014-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多