【发布时间】:2021-01-23 23:28:24
【问题描述】:
我有一个模型 School 与 has_many 关系与 PerformanceStats。
我发现自己经常在控制台和一些 rake 任务中编写此代码。
School.where(city: "Chicago").joins(:performance_stats).where(performance_stats: {year: "1819"}.where.not(performance_stats: {gr3_score: nil})
我也许可以通过在学校的 ActiveRecord 关系中包含一个方法来缩短此时间,所以我可以执行以下操作:
School.where(city: "Chicago").pstatjoin("1819","gr_score",nil)
def pstatjoin(year,x,y)
x.to_sym
self.joins(:performance_stats).where(performance_stats: {year: year}.where.not(performance_stats: {x => y})
end
但我不知道把这段代码放在哪里。
我在 SchoolsHelper 模块中试过这个:
Module SchoolHelper
Class School
def pstatjoin(year,x,y)
x = x.to_sym
self.joins(:performance_stats).where(performance_stats: {year: year}.where.not(performance_stats: {x => y})
end
end
end
我将模块包含在学校模型中
include SchoolsHelper
但这导致undefined method 'pj' for #<School::ActiveRecord_Relation:hexidecimal>)
有没有办法在不添加适用于每个 ActiveRecord_Relation 的代码的情况下做到这一点?
【问题讨论】:
标签: activerecord ruby-on-rails-5