如何在 sql 查询的 where 子句中使用 rails 对值数组生成 LIKE?

how generate LIKE on arrays of values in where clause of sql query with rails?

我有一个值数组:

words = ['foo', 'bar', 'baz']

我想使用 LIKE(而不是 "IN")自动生成 where 子句。

我现在做什么:

words = params[:content].split(' ').map { |w| "%#{w.strip}%" }

where = []
words.size.times do
  where << 'name LIKE ?'
end

tags = Tag.where(where.join(' OR '), *words)

生成正确的请求 SQL:

SELECT `tags`.* FROM `tags` WHERE (name LIKE '%foo%' OR name LIKE '%bar%' OR name LIKE '%baz%')

但这不是很好的方式...

当我想将数组值与等号进行比较时,我们可以这样做:

 Tag.where(name: words)

有可能做同样的事情但不生成 IN,而是生成多个 OR LIKE "%VALUE%"?怎么样?

在 postgresql 中它是这样工作的:

Tag.where("name iLIKE ANY ( array[?] )", words)

SQL RLIKE (正则表达式)

Tag.where("name RLIKE ?", words.join("|"))

SQL select(效率不是很高):

Tag.select{ |c| c.name =~ Regexp.new(words.join("|"), true) }

作为 Tag.rb 中的范围 (SQL)

scope :ilike_any, -> (words) {  where("name RLIKE ?", words.join("|")) }

这使您能够:

words = %w(word1 word2 word3)
Tag.ilike_any(words)