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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With