How to find substrings in a database using the Rails console?

As we know things. Where ("topic =?", "Blah") search for those that match "blah"

However, if I want to search for topics containing "bla"

How can I do it?

+6
ruby-on-rails
source share
1 answer

Here's a post that describes it.

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

However, the naive decision is susceptible to attacks due to lack of sanitation. If the user enters his own % wildcard character, he may receive data that you do not want to provide! The message above says that you manually sanitize these user inputs:

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

All Articles