Rails - Active Record 查询不查询变量分配(想要急切加载)

Rails - Active Record Query Not Querying on Variable Assignment (Want to Load Eagerly)

这是一个查询 returns 所有具有 rubric_item_evaluations 且 present=true 且具有带 @rubric_item.id

的标题项的问题提交
submissions_to_update = QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations => {:present => true , :rubric_item_id => @rubric_item.id})

然后我们销毁 rubric 项目

@rubric_item.destroy

然后我们遍历提交以重新评级

submissions_to_update.each do |submission|
  submission.grade!
end

但出于某种原因 question_submissions_update 之后在 .each 上被查询!到那时它不会查询正确的东西(返回一个空数组)。我很困惑...为什么它不查询初始变量赋值?

所以总的来说查询似乎发生在这里

submissions_to_update = QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations => {:present => true , :rubric_item_id => @rubric_item.id})
@rubric_item.destroy
# Query for submissions_to_update happening after I destroy the rubric item
submissions_to_update.each do |submission|
  submission.grade!
end

如有必要,我可以显示 SQL 语句!

更新 我有必要在销毁标题项之前实际执行查询。

当你这样写的时候:

submissions_to_update = QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations `=> {:present => true , :rubric_item_id => @rubric_item.id})

您正在构建一个 ActiveRecord::Relation,这是活动记录格式的查询本身,但最终您只是构建了一个查询而不是执行它。

然后你刚才说建立查询后就销毁@rubric_item,所以之前建立的查询之后就会出错。 @rubric_item.id 已不在数据库中,因此连接查询将找不到任何记录。

您需要在销毁物品之前检索问题,因此实际上您需要在销毁之前执行重新分级过程 rubric_item 例如:

submissions_to_update = QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations => {:present => true , :rubric_item_id => @rubric_item.id})
submissions_to_update.each do |submission|
  submission.grade!
end
@rubric_item.destroy

所以答案是在查询中调用 .load

QuestionSubmission.joins(:rubric_item_evaluations).where(:rubric_item_evaluations `=> {:present => true , :rubric_item_id => @rubric_item.id}).load

集合代理是延迟评估的,只有 运行 sql 在需要时查询。

因此,为了实际执行对变量赋值的查询(例如急切地),只需调用 .load.

有关文档的更多信息:http://apidock.com/rails/ActiveRecord/Relation/load