Accessing a class method from within an Active Record scope?

activerecord, ruby, ruby-on-rails, ruby-on-rails-4

Solution

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

Problem

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!

Original source