是否有一种方法来获得所有的记录,其中action_text为零



我的模型看起来像

class User < ApplicationRecord
has_rich_text :profile_text
end

现在我试图找到所有的记录,有一个空的profile_text

首先,看一下动作文本表

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中的补充记录对应于您想要查询的记录(空或nil)。

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表中,所以我查询负casewhere.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)
}

最新更新