I have a model School
with a has_many
relationship with PerformanceStats
.
I find myself often writing this code in console and throughout some rake tasks.
School.where(city: "Chicago").joins(:performance_stats).where(performance_stats: {year: "1819"}.where.not(performance_stats: {gr3_score: nil})
I though perhaps I could shorten this by including a method on a School's ActiveRecord Relation, so I could do something like:
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
But I'm not sure where to put this code.
I tried this in the SchoolsHelper Module:
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
and I included the module in the Schools Model
include SchoolsHelper
but this resulted in undefined method 'pj' for #<School::ActiveRecord_Relation:hexidecimal>)
Is there a way to do this without adding code that will apply to every ActiveRecord_Relation?
question from:
https://stackoverflow.com/questions/65865603/add-a-method-to-an-objects-activerecordrelation 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…