Monday, October 18, 2021

Using MySQL regular expressions in Rails ActiveRecord

Sometimes you want to filter the rows that not follow a given format.

For example, it was my case. I didn't get the rows that follow this format: [0-9]-wordhere

So, I did this:

my_result = MyModel.where("id = 1 AND (my_column NOT REGEXP ? AND my_column NOT REGEXP ?)", "[0-9]-wordone", "[0-9]-wordtwo")

This line will be transleted to:

SELECT * FROM my_table WHERE (id = 1 AND (my_column NOT REGEXP '[0-9]-wordone' AND my_column NOT REGEXP '[0-9]-wordtwo'))

Easy, right?

Happy coding :)