首页 > 解决方案 > 在 SmartListing Gem 中使用全文搜索进行分组和搜索时出现 PostgreSQL 错误

问题描述

我在 Rails 应用程序中使用 smartlisting gem 和 postgresql。该表显示了关联的元素列表,在某些情况下元素可以重复,但我只需要在表中显示该元素一次,但是当我将 DISTINCT 或 uniq 添加到活动记录时,它会在数组中转换和智能列表显示和错误。然后我尝试使用组来解决它,并且它有效!但是当我尝试使用 pg_scope 进行全文搜索时,pg 查询崩溃。这里的代码:

class Prospect < ActiveRecord::Base
  include PgSearch
  pg_search_scope :search_by_name,
                  against: [:name, :father_last_name, :mother_last_name],
                  associated_against: { user: [:first_name, :father_last_name,
                                               :mother_last_name] },
                  ignoring: :accents

  has_many :projects, through: :project_prospects, dependent: :destroy
  .
  .
  .
class User < ActiveRecord::Base
  has_many :project_prospect
  has_many :projects, through: :user_projects, dependent: :nullify
end

查询

search = User.find(id).prospects.select("prospects.*").group("prospects.id")
search = search.search_query("Say my name") if search_full_text.present? 

该小组致力于删除活动记录中的重复项,但是当需要全文搜索时,我收到下一个错误

PG::GroupingError: ERROR:  column "pg_search_ece0055f6ad1de91cd168e.rank" must appear in 
the GROUP BY clause or be used in an aggregate function 

LINE 1: ...168e.pg_search_id GROUP BY prospects.id  ORDER BY pg_search_...

标签: ruby-on-railspostgresql

解决方案


经过几个小时的搜索,这个问题的唯一解决方案是在全文搜索之后创建组,并在 SELECT 中的查询中添加一个名为“rank”的变量,如下所示:

search = User.find(id).prospects
if search_full_text.present? 
    search = search.search_query("Say my name")
                   .select("prospects.*").group("prospects.id, rank")
else
    search = search.select("prospects.*").group("prospects.id")
end

推荐阅读