简体   繁体   中英

refactor code to avoid N+1 query

I have my association like this

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

Problem

Everytime I call transcription_status it is executing N+1 query. Suggest me the way to refactor this code to prevent N+1 query limit?

Thanks

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

Transscription.includes(:transcription_status)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM