- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在运行 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/
问了这个问题How to reach CSS zen? ,我现在明白我遇到的问题大多与定位有关。我发现一些文章说 CSS 作为布局系统并不总是足够好。 http://echochamber.me/vi
我是一名优秀的程序员,十分优秀!