gpt4 book ai didi

ruby-on-rails - 预先加载和使用 'where' 方法时遇到问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:51 24 4
gpt4 key购买 nike

我正在运行 Ruby on Rails 3.1。我正在使用 includes 方法,我想了解为什么当我在急切加载的集合上调用 where 方法时,它会重新加载关联的对象,而不是仅仅在急切加载的集合。由于所有相关对象都已经预先加载,我希望 where 方法不会访问数据库以重新加载这些对象!

也就是说,我有以下内容:

article_categories =
article
.categories
.where(:user_id => @current_user.id)
.includes(:comments)

如果我跑

# CASE 1:

article_categories.each do |article_category|
article_category.comments.map(&:title)
end

预加载按预期工作:避免了“N + 1 查询问题”。但是,上面的代码还返回了:user_id == @current_user.id”的评论标题,但我根本不想检索那些。

因此,由于我认为通过使用预加载我已经获得了所有评论,所以我使用了进一步的 where(:user_id => @current_user.id) 语句,如下面的代码所示:

# CASE 2:

article_categories.each do |article_category|
article_category.comments.where(:user_id => @current_user.id).map(&:title)
end

但是,在这种情况下,预先加载不会按预期工作:不会避免“N + 1 查询问题”...但是注释有“:user_id == @current_user.id"!

我想使用“:user_id == @current_user.id”预先加载评论(如何利用预先加载来做到这一点?),我想了解为什么 where 语句会取消预加载效果。

最佳答案

在情况 1 中,where 子句仅适用于类别。如果您还希望它应用于评论,您可以这样做:

article_categories =
article
.categories
.includes(:comments)
.where('categories.user_id = ? AND comments.user_id = ?', @current_user.id, @current_user.id)

关于ruby-on-rails - 预先加载和使用 'where' 方法时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com