【问题标题】:Trouble on eager loading and using the 'where' method急切加载和使用“where”方法时遇到问题
【发布时间】:2012-03-26 14:35:42
【问题描述】:

我正在运行 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 查询问题”。但是,上面的代码也返回了带有 not:user_id == @current_user.id”的注释标题,但我根本不想检索那些。

因此,由于我认为通过使用预先加载我已经获得了所有 cmets,因此我使用了进一步的 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 查询问题”......但是 cmets 有“@987654329 @"!

我想使用“:user_id == @current_user.id”预加载 cmets(如何利用预加载的优势来实现这一点?)我想了解为什么 @ 987654331@ 语句取消急切加载效果。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1 eager-loading


    【解决方案1】:

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

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

    【讨论】:

    • where 方法“指的是”/“运行于”categories,而不是commentscategoriescomments 都具有 user_id 属性/列。
    • 所以您需要在类别和 cmets 上使用 where 子句?你的意思是?您的问题似乎是关于没有user_id == @current_user.id 的cmets 的事实。我的回答解决了这个问题。
    • 我的意思是我想检索所有categories.where(:user_id => @current_user.id) 并急切加载所有article.comments.where(:category_id => category_ids, :user_id => @current_user.id)category_ids 是提到的categories.where(:user_id => @current_user.id) 的数组。 P.S.:我不知道我是否清楚。
    • "有些 cmets 没有 user_id == @current_user.id"。是的。
    • 我在stackoverflow.com/questions/9629860/… 提出了一个更具体的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多