Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 898
JayX Avatar asked Dec 25 '10 20:12

JayX


People also ask

How do I view a database in Rails?

You can use rails dbconsole to view the database that your rails application is using. It's alternative answer rails db . Both commands will direct you the command line interface and will allow you to use that database query syntax.

How do I access the rails console?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .


1 Answers

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 + "%")
like image 162
P Shved Avatar answered Nov 15 '22 07:11

P Shved