簡體   English   中英

通過關聯使用 has_many 保存時檢測到 Rails 急切加載

[英]Rails eager loading detected when saving with has_many through association

Bullet gem 在創建時檢測到急切加載。 考慮以下模型:

class User < ActiveRecord::Base
  has_many :user_banks
  has_many :banks, through: :user_banks
end

class Bank < ActiveRecord::Base
  belongs_to :country
  belongs_to :currency

  has_many :user_posts
  has_many :users, through: :user_banks
end

class UserBank < ActiveRecord::Base
  belongs_to :user
  belongs_to :bank
end

在我的 controller 中,創建用戶時:

  # GET /user/new
  def new
    @user = User.new
  end

  # POST /users
  def create
    @user = User.new(user_params)

    if @user.save
      redirect_to user_path(@user), notice: I18n.t('views.action.created')
    else
      render :new
    end
  end

  private

  def user_params
    params.fetch(:user, {}).permit(:name, :email, bank_ids: [])
  end

我有一個錯誤;

Bullet::Notification::UnoptimizedQueryError:
  user: ruby
  POST /admin/users
  USE eager loading detected
    Bank => [:country]
    Add to your query: .includes([:country])
  Call stack
    /src/app/controllers/admin/users_controller.rb:36:in `create'

不幸的是,通過關聯急切加載 has_many 的 Rails 代碼有點錯誤。 我該如何解決這個問題? 渴望加載Bankcountrycurrency

如果您將在 Rails 控制台中嘗試這樣的事情;

[1] pry(main)> User.new(name: 'test', email: 'test@test.com', bank_ids: [1, 2]).save!

  Country Load (1.3ms)  SELECT `countries`.`id`, `countries`.`created_at`, `countries`.`updated_at`, `countries`.`code` FROM `countries` WHERE `countries`.`id` = 1 LIMIT 1
  Currency Load (0.4ms)  SELECT `currencies`.* FROM `currencies` WHERE `currencies`.`id` = 1 LIMIT 1
  Country Load (1.3ms)  SELECT `countries`.`id`, `countries`.`created_at`, `countries`.`updated_at`, `countries`.`code` FROM `countries` WHERE `countries`.`id` = 1 LIMIT 1
  Currency Load (0.4ms)  SELECT `currencies`.* FROM `currencies` WHERE `currencies`.`id` = 1 LIMIT 1
  User Create (0.5ms)  INSERT INTO `users` (`name`, `email`, `created_at`, `updated_at`) VALUES ('test', 'test@test.com', '2020-06-25 06:18:50', '2020-06-25 06:18:50')
  UserBank Create (1.0ms)  INSERT INTO `user_banks` (`user_id`, `bank_id`, `created_at`, `updated_at`) VALUES (1, 1, '2020-06-25 06:18:50', '2020-06-25 06:18:50')
  UserBank Create (0.4ms)  INSERT INTO `user_banks` (`user_id`, `bank_id`, `created_at`, `updated_at`) VALUES (1, 2, '2020-06-25 06:18:50', '2020-06-25 06:18:50')

嘗試:

User.new(name: 'test',
         email: 'test@test.com',
         banks: Bank.eager_load(:country, :currency).find([1, 2])
        ).save!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM