Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 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 Answer

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! ??


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...