JayX
JayX

Reputation: 1784

How do I search substrings in a database using Rails console?

As we know Things.where("topic = ?","blah") searches for topics that match "blah"

However, what if I want to search for topics that contain "bla"

How should I do this?

Upvotes: 7

Views: 6113

Answers (1)

P Shved
P Shved

Reputation: 99264

Here's a post that describes it.

Basically, you use SQL LIKE expression to match strings that contain something. Using where("topic like ?", "%bla%") would do the trick.

However, naive solution is prone to attacks due to lack of sanitizing. If user types its own % wildcard character, he can get data you don't mean to provide! The post above suggests that you manually sanitize such user inputs:

escaped_str =  "bla".gsub ('%', '\%').gsub ('_', '\_')
Topic.where("topic like ?", "%" + escaped_str + "%")

Upvotes: 11

Related Questions