Ruby on Rails ActiveRecord Query Interface ActiveRecord case insensitive search

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

If you need to search an ActiveRecord model for similar values, you might be tempted to use LIKE or ILIKE but this isn't portable between database engines. Similarly, resorting to always downcasing or upcasing can create performance issues.

You can use ActiveRecord's underlying Arel matches method to do this in a safe way:

addresses = Address.arel_table
Address.where(addresses[:address].matches("%street%"))

Arel will apply the appropriate LIKE or ILIKE construct for the database engine configured.



Got any Ruby on Rails Question?