首页 > 解决方案 > Rails 包含 has_many,通过子弹 gem 避免 eger 加载 n+1

问题描述

我的模型是这样的:

class ThreeDModel < ApplicationRecord
  has_many :three_d_model_animations
  has_many :animations, through: :three_d_model_animations
  has_many :three_d_model_images, dependent: :destroy
  has_many :three_d_garments
  has_one :model_efm
  has_one :model_edm
end

第二:

    class ThreeDModelAnimation < ApplicationRecord
      belongs_to :animation
      belongs_to :three_d_model
      validates_presence_of :animation_file
      #validates_presence_of :motion
      mount_uploader :animation_file, ThreeDModelAnimationUploader
      enum animation_motions: {
          'Run': 'run',
          'Turn Aroun (100 Frames)': 'turn_around_100_frames',
          'Turn Around (300 Frames)': 'turn_around_300_frames',
          'Walk (58 Frames)': 'walk_58_frames',
          'Walk (92 Frames)': 'walk_92_frames'
      }
    end

第三:

class Animation < ApplicationRecord
  has_many :three_d_model_animations
  has_many :three_d_models, through: :three_d_model_animations
  mount_uploader :video, AnimationVideoUploader
  validates_presence_of :video

  validates :name, :frames, :loop_start, :loop_end, presence: true
end

现在我的查询是:

    @model = ThreeDModel.where(id: params[:id]).includes(:model_efm, :model_edm, :three_d_model_images, :three_d_model_animations, :animations).last

它通过子弹宝石给出以下消息:

AVOID eager loading detected
  ThreeDModel => [:three_d_model_animations, :animations]

有没有更好的方法可以避免 n+1。提前致谢

标签: ruby-on-rails-4rubygemsruby-on-rails-5ruby-2.4

解决方案


推荐阅读