Search code examples
ruby-on-railsrubyactiverecordmodelactive-record-query

Rails ActiveRecord model scope with joins on has_many associations


I’m currently setting up a scope in my Rails model to be used by ActiveAdmin. The scope I want to build should find every Job that has a survey_date in the past, with a Job.survey present, and no Job.quotes present.

Here is an abbreviated version of my Job model:

has_many :quotes
has_many :surveys

scope :awaiting_quote, lambda { joins(:surveys, :quotes).where('survey_date < :current_time AND surveys.id IS NOT NULL AND quotes.id IS NULL', { current_time: Time.current }) }

How should I change my scope so that it correctly finds the revelant Job records?


Solution

  • Rails 5 introduced left_outer_joins method that can be used

    scope :awaiting_quote, -> { joins(:surveys).left_outer_joins(:quotes).where('yada yada') }