How to Build a Wildcard Query in Rails

Feature thumb snip20201104 34

Building out wilcard queries is a common requirement in many web applications. However, it's important to set them up properly to prevent hackers from performing tasks such as deleting or updating records they shouldn't have access to.

The Rails ActiveRecord ORM system offers a great way to perform secure, wilcard queries. However, the documentation has a different name for the process, so it can be a little tricky to find if you're new to the framework, Rails calls wilcard queries: array conditions. An example query is below:

query = 'some blog name'
Blog.where('name ILIKE ?', "%#{query}%")

That will search through the blogs table and return any and all matches that include the phrase included in the query variable. By placing the string: 'name ILIKE ?' in the where method, Rails auto escapes any malicious attempts at attacking the database, so it's find to take in user query data.

You can view the documentation along with some additional code examples below: