Rails检查文本中的多个单词作为查询



目前,我正在尝试使用以下循环检查存储在我的数据库中的评论文本。

def bad_words_check 
bad_words = ["covid", "corona", "coronavirus", "pandemic", "quarantine", "lockdown", "virus"]
bad_words.each do |word|
Comment.where("comment_text ~* ?", word).update(flag_covid: true)
end
end

然而,这似乎作为一个无限循环运行。在我的rails控制台中,在单行查询中单独运行每个单词会更快、更有效。

Comment.where("comment_text ~* ?", "covid").update(flag_covid: true)

肯定有更好的方法吧?

如果你只是想检查整个注释是否是一个坏词:

Comment.where(comment_text: bad_words)

这与

相同
Comment.where("comment_text ILIKE ANY (ARRAY[?])", bad_words) # for Postegres
Comment.where("comment_text LIKE in ?", bad_words) # for MySql

但是,如果该单词可以包含在注释中,则应该循环并检查每个注释:

bad_words.each |bad_word| do
Comment.where("comment_text LIKE in ?", '%#{bad_word}%')
end

您可以使用ILIKE和ANY来完成此操作:

bad_words = bad_words.map { |word| "%#{word}%" }
Comment.where("comment_text ILIKE ANY (ARRAY[?])", bad_words)
.update(flag_covid: true)

最新更新