简体   繁体   中英

Rails eager loading detected when saving with has_many through association

Bullet gem detected an eager loading on create. Consider the following models:

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

In my controller, when creating user:

  # 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

I've got an error;

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'

The Rails code that eager loads has_many through associations is unfortunately a bit buggy. How do I solve this? to eager load the country and currency of the Bank .

If you will try in Rails console something like this;

[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')

Try:

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

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