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?
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.
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 .
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 + "%")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With