【发布时间】:2021-12-03 23:40:46
【问题描述】:
我的模型看起来像
class User < ApplicationRecord
has_rich_text :profile_text
end
现在我正在尝试查找所有具有空 profile_text 的记录
【问题讨论】:
标签: ruby-on-rails activerecord actiontext
我的模型看起来像
class User < ApplicationRecord
has_rich_text :profile_text
end
现在我正在尝试查找所有具有空 profile_text 的记录
【问题讨论】:
标签: ruby-on-rails activerecord actiontext
首先,看一下动作文本表
create_table :action_text_rich_texts do |t|
t.string :name, null: false
t.text :body, size: :long
t.references :record, null: false, polymorphic: true, index: false
t.timestamps
t.index [ :record_type, :record_id, :name ],
name: "index_action_text_rich_texts_uniqueness",
unique: true
end
其中,name 对应于富文本属性(在你的情况下,它是profile_text),record(类型和id)对应于你的类User。
所以在我看来,一种方法是从所有存在正文的动作文本中提取record_ids,并且不在此record_ids 中的补充记录对应于记录(空或无)你要查询。
scope :without_rich_text, -> {
ids = ActionText::RichText
.where(name: 'profile_text', record_type: 'User')
.where.not(body: [nil, ""])
.pluck(:record_id)
where.not(id: ids)
}
User.without_rich_text
User.without_rich_text.first
User.where(department: [1,2,3]).without_rich_text
请注意,我试图涵盖profile_text 根本不存在于action-text 表中的用户的情况,因此我使用否定情况where.not 进行查询。
如果您确定您的所有用户 profile_text 都存在于 action-text 表中,并且您只想过滤所有空记录,那么您可以使用正例进行查询
scope :without_rich_text, -> {
ids = ActionText::RichText
.where(name: 'profile_text', record_type: 'User')
.where(body: [nil, ""])
.pluck(:record_id)
where(id: ids)
}
【讨论】: