提问人:aldm 提问时间:11/7/2023 最后编辑:shadowspawnaldm 更新时间:11/8/2023 访问量:54
没有 N+1 查询,没有在 Rails 中预加载关联
No N+1 query without preloading associations in Rails
问:
我在 Rails 中遇到了一个奇怪的行为,我期望 N+1 查询但没有得到它:)
模型
Post
has_one :moderated_record
ModeratedRecord
belongs_to :record, polymorphic: true
belongs_to :moderation_flow
ModerationFlow
has_many :moderation_steps
ModerationLog
belongs_to :moderated_record
belongs_to :user
belongs_to :moderation_step
ModerationStep
belongs_to :moderation_flow
has_many :moderation_logs
现在代码如下
posts.filter_map do |post|
post.moderated_record.moderation_flow.moderation_steps.find do |step|
step.moderation_logs.all?(:¬_moderated_yet?)
end
end
不执行 n+1,而是获取条件类似于 () 中 id 的所有实体
例如:
SELECT * from moderation_steps where moderation_flow_id IN (...)
SELECT * from moderation_logs where moderation_step_id IN (...)
我用这些查询创建了一个规范,我看到没有 n+1
我知道这不会生成 n+1,但我希望在每次迭代(针对每个帖子)中执行新查询has_one
post.moderated_record.moderation_flow.moderation_steps
对此有什么意见吗?
值得一提的是,我正在使用 ActiveRecord 和 Postgres 数据库
答: 暂无答案
评论
.to_sql
posts
.includes