You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置pg_search_scope使其包含软删除的Item关联记录?

解决方案

要让pg_search的搜索范围包含软删除的Item,你需要在pg_search_scope中指定关联查询时使用acts_as_paranoid提供的with_deleted scope,以此取消默认的软删除过滤规则。

修改后的log.rb代码如下:

class Log < ApplicationRecord
  include PgSearch::Model

  # associations
  belongs_to :item

  # scopes
  pg_search_scope :search_log, 
    associated_against: { item: %i[title] },
    # 添加这一行,指定关联Item时包含软删除记录
    associated_scope: { item: :with_deleted },
    using: { tsearch: { prefix: true } }

  scope :list_feed, lambda { |search_text = nil|
    logs = all
    logs = logs.search_log(search_text) if search_text.present?
    logs
  }
end

原理说明

acts_as_paranoid会自动给模型的关联查询添加deleted_at IS NULL的过滤条件,默认排除软删除的记录。通过pg_search的associated_scope选项,我们可以为关联的Item模型指定with_deleted scope,该scope会移除默认的软删除过滤,让pg_search在构建全文搜索查询时包含所有Item(无论是否软删除)的title字段。

内容的提问来源于stack exchange,提问作者a.fahmiin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 04:40:55