我有这样的协会
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
查询限制?
由于
答案 0 :(得分:3)
您必须使用includes
预加载数据:
Transscription.includes(:transcription_status)