我试图从模型中调用lib/
目录中文件中的全局方法。我已经尝试过解决问题,问题仍然存在。
该应用是在Ruby on Rails 5.2.1和Ruby 2.5.3中开发的
# Expense model
class Expense < ApplicationRecord
include Helpers
def self.quantity_this_month
select { |e| year_month(e.date) == year_month(Date.today)
}.count
end
end
# Helper in lib/ directory
module Helpers
def year_month(date)
date.strftime('%Y/%m')
end
end
# in console
Expense.quantity_this_month
直接在模型方法中实现帮助程序的代码可得到预期的结果,但现在它显示此错误:
undefined method `year_month' for #<Class:0x00007f2f6f0e4b88>
有什么想法吗?
答案 0 :(得分:2)
您需要使用extend
而不是include
,因为要从中调用的方法是 class方法。
此外,仅需注意,您的self.quantity_this_month
将 all 费用记录加载到内存中,但是可以在单个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