user1883793
user1883793

Reputation: 4199

ActiveRecord regular-expression search by whole word

I want to search ActiveRecord model Product by keyword, but I only want to match whole words in its description instead of arbitrary substrings.

Say I have the string

'the packaging May Vary'

as a Product's description, then a search using keyword 'aging' should not match, but a search for 'packaging' should match. So match by words, beginning or end of the string. I want to do something like this:

Product.where("description ~* ?", "Regexp")

What should I replace the Regexp with, something like "%[^|| ]#{string}[$|| ]%"?

Upvotes: 0

Views: 357

Answers (1)

lunr
lunr

Reputation: 5269

Product.where("description ~* ?", "\m#{string}\M")

\m matches only at the beginning of a word and \M matches only at the end of a word. More info here: http://www.postgresql.org/docs/9.0/static/functions-matching.html

Upvotes: 1

Related Questions