【发布时间】:2020-10-15 13:45:16
【问题描述】:
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
在我的控制器中,创建用户时:
# 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 代码有点错误。
我该如何解决这个问题?急切加载Bank 的country 和currency。
如果你会在 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')
【问题讨论】:
-
请同时包含来自项目符号的调用堆栈,创建操作不会从数据库中获取任何内容,因此我们需要更多上下文。也可能包括显示操作和视图,因为这是您成功保存用户后重定向的位置。
-
Call stack来自 create 方法中的if @user.save行。我觉得对这个问题加观点太多了。 -
很遗憾,您在此处显示的代码无法回答您的问题。
-
我更新了我的问题。我这里的问题是
N+1创建时如何解决 -
您确定在渲染显示视图时重定向后没有生成项目符号警告吗?
标签: ruby-on-rails ruby