我目前正在Rails模型中設置一個作用域以供ActiveAdmin使用。我想構建的範圍應該會找到每個Job
,它們過去都有survey_date
,目前有Job.survey
,並且沒有Job.quotes
。Rails ActiveRecord模型範圍與has_many關聯上的連接
這裏是我的Job
模型的簡化版本:
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 }) }
我應該如何改變我的範圍,使其正確地找到revelant Job
記錄?
請注意'joins'將創建一個INNER JOIN,這意味着'quotes.id IS NULL'沒有影響,並且這些作業永遠不會顯示try'includes(:surveys,:quotes).where(' survey_date <:current_time AND surveys.id IS NOT NULL AND quotes.id IS NULL',{current_time:Time.current})'這將創建2個LEFT OUTER JOIN,並且可能對您更好。關於關聯加載以及這些方法如何工作,這是一篇很棒的[文章](http://blog.bigbinary.com/2013/07/01/preload-vs-eager-load-vs-joins-vs-includes.html) – engineersmnky