简体   繁体   中英

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?

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 + "%")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM