重构代码,以避免N + 1查询

时间:2014-06-25 07:57:53

标签: ruby-on-rails ruby ruby-on-rails-3.2

我有这样的协会

models/transcription.rb

class Transcription < ActiveRecord::Base
  belongs_to :transcription_status, :class_name => "TranscriptionStatus",
    :inverse_of => :transcriptions


  # Initialize to "new" status if a status isn't already set
  def setup_status
    if transcription_status.nil?  # this method is taking lots of execution time ( N + 1 )
      status = TranscriptionStatus.find_by_state("new")
      if status
        self.transcription_status = status
      end
    end
  end
end

models/transcription_status.rb

class TranscriptionStatus < ActiveRecord::Base
  has_many :transcriptions, :inverse_of => :transcription_status
end

问题

每次调用transcription_status时,都会执行N+1查询。建议我重构此代码以防止N+1查询限制?

由于

1 个答案:

答案 0 :(得分:3)

您必须使用includes预加载数据:

Transscription.includes(:transcription_status)