Can I use Regex in Rails .where()?

activerecord, mysql, ruby, ruby-on-rails, ruby-on-rails-4

Solution

Since you are using mysql, you can leverage it's support for regular expressions. You'll want to switch to the `RLIKE` operator and adjust your operands accordingly.

For example, using your existing structure, you could use the following

filter_letter = (params[:letter] =~ /[a-z]/i ? params[:letter] : "[^a-z]" )
@artists = Artist.where("name RLIKE ?", "^#{filter_letter}")

See http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html for more information. Note in particular that mysql regular expressions are not case sensitive, so you don't need to worry about that issue.

Problem

I have a menu that shows the first letter of various artists: `A B C D E F ...` It basically is a way to filter many artists by first letter of name. The problem some begin with a symbol, a number, or anything other than `[a-z]`. So I want it to be `# A B C D E F ...` But how do I go about making that work with my where clause? ``` filter_letter = (params[:letter] =~ /[a-z]/i ? params[:letter] : "something_here" ) @artists = Artist.where("name LIKE ?", "#{filter_letter}%") ```

Original source