Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a class method from within an Active Record scope?

I am having issues with the scope in this model and I'm at a loss at how best to fix it. I would like to call the distinct_mechanics_sql from within the scope to keep things cleaner, but when I run this I get an "undefined local variable or method" error. Here is the model:

class Mechanics < ActiveRecord::Base
  scope :with_moz, -> { joins("JOIN (#{distinct_mechanics_sql}) mh ON mh.mechanic_id = mechanics.id") }

  def distinct_mechanics_sql 
    """
    SELECT DISTINCT ON (mechanic_id) *
    FROM checkups
    ORDER BY mechanic_id, updated_at DESC
    """
  end

end

Any help would be greatly appreciated!

like image 822
newUserNameHere Avatar asked Oct 21 '25 02:10

newUserNameHere


1 Answers

Scopes are same as class methods, so within the scope you are implicitly call another class methods. And your distinct_mechanics_sql is an instance method, to use it inside a scope declare it as:

def self.distinct_mechanics_sql

or

def Mechanics.distinct_mechanics_sql

or

class << self 
  def distinct_mechanics_sql
    ...
  end
end
like image 56
Rustam A. Gasanov Avatar answered Oct 23 '25 02:10

Rustam A. Gasanov