What I’m trying to do is to write a query like the following:
Foo.where("bar LIKE 'bam\_%'")
The idea being that this would return all the rows where bar, which contains a string, starts with ‘bam_’ and then is of an indeterminate length thereafter. I’ve tried this as a pure MySQL query in the MySQL workbench and it seems to work as expected. When I do this in RoR, however, it seems to ignore the escape character completely and treats underscore like the wildcard that it really is. Is there not a way to write this in Rails where I can include the underscore in my query? Thanks.
The backslash is an escape character in Ruby strings, so
\_means to treat the_as literal. Since_is treated as literal anyway, this does nothing, except to treat the\as if it wasn’t there. One of the ways to actually have a backslash in your string given by a Ruby literal is to escape it by using another backslash (e.g."bar LIKE 'bam\\_%'").