sql - a proper way to escape %% when building LIKE queries in Rails 3 / ActiveRecord -
i want match url field against url prefix (which may contain percent signs), e.g. .where("url ?", "#{some_url}%"). what's rails way?
if understand correctly, you're worried "%" appearing inside some_url , rightly so; should worried embedded underscores ("_") too, they're version of "." in regex. don't think there rails-specific way of doing you're left gsub:
.where('url ?', some_url.gsub('%', '\\\\\%').gsub('_', '\\\\\_') + '%') there's no need string interpolation here either. need double backslashes escape meaning database's string parser parser see simple "\%" , know ignore escaped percent sign.
you should check logs make sure 2 backslashes through. i'm getting confusing results checking things in irb, using 5 (!) gets right output don't see sense in it; if see sense in 5 of them, explanatory comment appreciated.
update: jason king has kindly offered simplification nightmare of escaped escape characters. lets specify temporary escape character can things this:
.where("url ? escape '!'", some_url.gsub(/[!%_]/) { |x| '!' + x }) i've switched block form of gsub make bit less nasty.
this standard sql92 syntax, work in db supports that, including postgresql, mysql , sqlite.
embedding 1 language inside bit of nightmarish kludge , there's not can it. there ugly little bits have grin , bear.
Comments
Post a Comment