tomb
tomb

Reputation: 1436

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?

Upvotes: 1

Views: 200

Answers (1)

r4cc00n
r4cc00n

Reputation: 2137

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

Upvotes: 1

Related Questions