没有 N+1 查询,没有在 Rails 中预加载关联

No N+1 query without preloading associations in Rails

提问人:aldm 提问时间:11/7/2023 最后编辑:shadowspawnaldm 更新时间:11/8/2023 访问量:54

问:

我在 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?(:&not_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_onepost.moderated_record.moderation_flow.moderation_steps

对此有什么意见吗?

值得一提的是,我正在使用 ActiveRecord 和 Postgres 数据库

SQL Ruby-on-Rails Ruby

评论

0赞 Beartech 11/8/2023
您是否尝试过查看它生成的查询?.to_sql
0赞 aldm 11/8/2023
@dbugger Rails 的版本是 7.0.8 我认为这个问题非常详细和清晰
0赞 aldm 11/8/2023
@Beartech是的,试过了,还创建了如前所述的规范,但没有 n+1 查询
0赞 Marian13 11/28/2023
@aldm 你能说明一下变量是如何设置的吗?我想,它可能有.这就是为什么 N + 1 没有发生的原因。posts.includes

答: 暂无答案