2

I have an array of value :

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

I want autogenerate a where clause with LIKE (and not "IN").

What I do for now :

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

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

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

the correct request SQL is generate :

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

but it's not realy nice way...

when I want compare array values with equals, we can just do :

 Tag.where(name: words)

There is a possibility to do same thing but not generate IN, but multiple OR LIKE "%VALUE%" ? How?

1 Answer 1

11

In postgresql it works like this:

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

SQL RLIKE (REGEX)

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

SQL select (not very efficient):

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

As a scope in Tag.rb (SQL)

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

That enables you to do:

words = %w(word1 word2 word3)
Tag.ilike_any(words)
Sign up to request clarification or add additional context in comments.

1 Comment

There is a solution to RLIKE multiple properties like "name" and "description" for exemple, in same time?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.