Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 模型的辅助对象中存在未定义的方法错误_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 模型的辅助对象中存在未定义的方法错误

Ruby on rails 模型的辅助对象中存在未定义的方法错误,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图从模型中调用lib/目录中文件中的全局方法。我已经试过了,但问题仍然存在 该应用程序是在RubyonRails 5.2.1和Ruby2.5.3中开发的 费用模型 课程费用

我试图从模型中调用lib/目录中文件中的全局方法。我已经试过了,但问题仍然存在

该应用程序是在RubyonRails 5.2.1和Ruby2.5.3中开发的

费用模型 课程费用<申请记录 包括助手 定义本月的自我数量 选择{e | year|u month.date==year|u monthDate.today }.伯爵 终止 终止 lib/目录中的Helper 模块助手 def年月日 日期。strftime“%Y/%m” 终止 终止 控制台中 本月费用、数量 直接在model方法中实现helper的代码可以得到预期的结果,但现在它显示了以下错误:

undefined method `year_month' for #<Class:0x00007f2f6f0e4b88>
有什么想法吗?

您需要扩展而不是包含,因为您要从中调用它的方法是类方法

另外,请注意,您的self.quantity\u this\u月会将所有费用记录加载到内存中,但也可以在单个SQL查询中进行日期筛选和计数。以下是MySQL中的操作方式,这可能与其他数据库略有不同:

class Expense < ApplicationRecord
  extend Helpers # <~~~~~~~ changed to extend
  def self.quantity_this_month
    where(
      "DATE_FORMAT(date, '%Y/%m') = ?",
      year_month(Date.today)
    ).count
  end
end

天才感谢代码的改进,我正在使用postgres来格式化日期:to_chardate,'YYYY/MM'