If I understand correctly, you are worried about the "%" appearing inside some_url and correctly; you should also worry about the built-in underscores ("_"), they are the LIKE version of ".". in regular expression. I don’t think there is any specific Rails way, so you will stay with gsub :
.where('url like ?', some_url.gsub('%', '\\\\\%').gsub('_', '\\\\\_') + '%')
There is no need for string interpolation. You need to double the backslash to avoid their value from the database parser, so that the LIKE parser sees a simple "\%" and knows to ignore the sign with the escaped percentage.
You should check your logs to make sure that two backslashes pass. I get confusing results from checking things in irb using five (!) It gets the correct output, but I don't see the point in it; if anyone sees the point in five of them, an explanatory comment will be appreciated.
UPDATE : Jason King has kindly offered simplification for the nightmare of runaway characters. This allows you to specify a temporary escape character so you can do things like this:
.where("url LIKE ? ESCAPE '!'", some_url.gsub(/[!%_]/) { |x| '!' + x })
I also switched to the gsub block form to make it less annoying.
This is the standard syntax for SQL92, so it will work in any database that supports it, including PostgreSQL, MySQL, and SQLite.
Embedding one language inside another is always a nightmare cudd, and you cannot do it. There will always be ugly pieces that you just need to smile and carry.
mu is too short Apr 18 2018-11-21T00: 00Z
source share