【问题标题】:ActiveRecord: can't use `pluck` after `where` clause with eager-loaded associationsActiveRecord:不能在 `where` 子句后使用 `pluck` 与急切加载的关联
【发布时间】:2013-01-06 08:39:06
【问题描述】:

我有一个应用程序,其中包含多个 Post 模型,每个模型 belongs_to 一个 User 模型。发布这些帖子时,会创建一个 PublishedPost 模型,该模型将 belongs_to 与相关的 Post 模型相结合。

我正在尝试构建一个 ActiveRecord 查询来查找与用户名匹配的已发布帖子,然后获取这些已发布帖子的 ID,但是当我在急切之后尝试使用 pluck 方法时出现错误- 加载我的关联并使用where 方法搜索它们。

这是我的控制器(部分):

class PublishedPostsController < ApplicationController

  def index
    ar_query = PublishedPost.order("published_posts.created_at DESC")

      if params[:searchQuery].present?
        search_query = params[:searchQuery]
        ar_query = ar_query.includes(:post => :user)
                           .where("users.name like ?", "%#{search_query}%")
      end

    @found_ids = ar_query.pluck(:id)

  ...

  end

end

当pluck 方法被调用时,我得到了这个:

ActiveRecord::StatementInvalid: Mysql2::Error: Unknown column 'users.name' in 'where clause': SELECT id FROM `published_posts`  WHERE (users.name like '%Andrew%') ORDER BY published_posts.created_at DESC

我可以得到我正在寻找的结果

@found_ids = ar_query.select(:id).map{|r| r.id}

但我宁愿使用pluck,因为这似乎是一种更清洁的方式。不过,我不知道为什么它不起作用。有什么想法吗?

【问题讨论】:

    标签: sql ruby-on-rails-3 activerecord arel


    【解决方案1】:

    您需要并且应该在此处使用joins 而不是includes。

    这两个函数非常相似,只是来自joins 的数据不会在查询结果中返回,而includes 中的数据是。

    在这方面,includes 和 pluck 有点对立。一个说尽可能把所有数据都还给我,另一个说只给我一点点。

    由于您只想要少量数据,因此您想做joins。 (奇怪的是,select 似乎有些对立仍然有效,但在这种情况下,您需要消除对 id 的歧义。)

    在控制台中尝试一下,您会看到 includes 会导致类似这样的查询:SELECT "posts"."id" as t0_ro, "posts"."text" as t0_r1, "users"."id" as t1_r0, "users"."name" as t1_r1 ... 当您添加 pluck 语句时,所有那些疯狂的 tx_ry 列都会消失并被替换由您指定的任何内容。

    我希望这会有所帮助,但如果不是,也许这个 RailsCast 可以。它在 5 分钟左右进行解释。

    http://railscasts.com/episodes/181-include-vs-joins

    【讨论】:

      【解决方案2】:

      如果您是通过搜索“rails pluck ambiguous column”来到这里的,您可能想知道您可以将 query.pluck(:id) 替换为:

      query.pluck("table_name.id")
      

      【讨论】:

      • 是的!我不知道为什么这不在文档中?至少我没看到。
      【解决方案3】:

      即使没有 pluck 调用,您的查询也无法正常工作。

      原因是,您的 WHERE 子句包含引用用户表的文字 SQL,Rails 没有注意到它并决定使用多个查询并加入内存( .preload() )而不是加入数据库级别( .eager_load() ):

      SELECT * from published_posts WHERE users.name like "pattern" ORDER BY published_posts.created_at DESC
      SELECT * from posts WHERE id IN ( a_list_of_all_post_ids_in_publised_posts_returned_above )
      SELECT * from users WHERE id IN ( a_list_of_all_user_ids_in_posts_returned_above )
      

      3 个查询中的第一个失败,这是您得到的错误。

      要强制 Rails 在此处使用 JOIN,您应该使用显式 .eager_load() 而不是 .includes(),或者添加 .references() 子句。

      除此之外,@Geoff 的回答是,您实际上并不需要 .includes(),而是需要 .joins()。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-05
        • 1970-01-01
        • 2010-12-01
        • 1970-01-01
        • 2017-08-28
        • 2014-11-14
        • 2020-09-12
        • 2020-03-08
        相关资源
        最近更新 更多