Rails中如何查询has_rich_text关联的profile_text为空的所有记录
可行实现方案
Rails 的 has_rich_text 会自动把富文本内容存储到 action_text_rich_texts 多态表中,关联名称为 #{属性名}_rich_text,你可以通过以下几种方式实现查询:
- 仅查询从未存储过 profile_text 的记录(无关联富文本记录)
# 通用写法,兼容所有Rails版本 User.left_joins(:profile_text_rich_text).where(action_text_rich_texts: { id: nil }) # Rails 7+ 简化写法 User.where.missing(:profile_text_rich_text)
- 查询所有 profile_text 为空的记录(包含「无关联记录」和「有关联记录但内容为空」两种场景)
User.left_joins(:profile_text_rich_text) .where("action_text_rich_texts.id IS NULL OR TRIM(action_text_rich_texts.body) = ''")
- 封装为模型 scope 复用
你可以直接把查询逻辑写到 User 模型里,后续调用更方便:
class User < ApplicationRecord has_rich_text :profile_text scope :with_empty_profile_text, -> { left_joins(:profile_text_rich_text) .where("action_text_rich_texts.id IS NULL OR TRIM(action_text_rich_texts.body) = ''") } end # 调用方式 User.with_empty_profile_text
- 特殊场景处理:过滤仅含空白富文本标签的空内容
如果你的空富文本存储后是类似<p><br></p>这类空标签结构,可以用正则匹配过滤:
User.left_joins(:profile_text_rich_text) .where("action_text_rich_texts.id IS NULL OR action_text_rich_texts.body ~ ?", "^\\s*(<p>\\s*(<br>)?\\s*</p>\\s*)*$")
内容的提问来源于stack exchange,提问作者MZaragoza
相关产品推荐
相关产品推荐

