Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 views
in Technique[技术] by (71.8m points)

activerecord - Add a method to an Object's ActiverecordRelation

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think a good approach/fit for this problem are definitely scopes, with a scope you can save some time and comply with the DRY principle, so you can define a scope within your School model as below:

scope :my_awesome_scope, ->(year, x, y) {joins(:performance_stats).where(performance_stats: {year: year}.where.not(x => y)}

Then you can use it everywhere like below:

School.my_awesome_scope(year, x.to_sym, y)

or even: School.where(...).my_awesome_scope(year, x.to_sym, y)

Hope this helps! ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...