質問

How can I create an arel query, or even straight sql query, that returns a search term within a string, but only when the term is a single word (and not part of another word).

As seen below, I've tried LIKE for the search, [[:<:]] [[:>:]] to set the word boundary, and % as wildcards for the rest of the string... though this doesn't work.

Post.where("title LIKE :keyword", {keyword: "%[[:<:]]#{keyword}[[:>:]]%"})

For reference I'm on ruby 2.1, rails 4.

役に立ちましたか?

解決

Word boundaries are part of regular expressions, which SQL doesn't have by default. You need to add regular expression support in order to do what you're trying to do (see How do I use regex in a SQLite query? for details).

Also, to use regular expressions once you've added support for that, replace "LIKE" with "REGEXP" - you don't use "LIKE" with regular expressions.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top