Search code examples
ruby-on-railsregexactivemodel

idiomatic way to do regular expression searches in rails models?


in my rails controller, i would like to do a regular expression search of my model. my googling seemed to indicate that i would have to write something like:

Model.find( :all, :condition => ["field REGEXP '?' " , regex_str] )

which is rather nasty as it implies MySQL syntax (i'm using Postgres).

is there a cleaner way of forcing rails (4 in my case) to do a regexp search on a field?

i also much prefer using using where() as it allows me to map my strong parameters (hash) directly to a query. so what i would like is something like:

Model.where( params, :match_by => { 'field': '~' } )

which would loosely translate to something like (if params['field'] = 'regex_str')

select * from models where field ~ regex_str

Solution

  • Unfortunately, there is no idiomatic way to do this. There's no built-in support for regular expressions in ActiveRecord. It'd be impossible to do efficiently unless each database adapter had a database-specific implementation, and not all databases support regular expression matches. Those that do don't all support the same syntax (for example, Postgres doesn't have the same regexp syntax as Ruby's Regexp class).

    You'll have to roll your own using SQL, as you've noted in your question. There are alternatives, however.

    For a Postgres-specific solution, check out pg_search, which uses Postgres's full text search capabilities. This is very fast and supports fuzzy searching and some pattern matching.

    elasticsearch requires more setup, but is incredibly fast, with some nice gems to make your life easier. Here's a RailsCasts episode introducing it. It requires running a separate server, but it's not too hard to get started, and it's powerful. Still no regular expressions, but it's worth looking at.

    If you're just doing a one-off regexp search against a single field, SQL is probably the way to go.