I want to match a url field against a url prefix (which may contain percent signs), e.g. .where("url LIKE ?", "#{some_url}%"). What's the most Rails way?
.where("url LIKE ?", "#{some_url}%")
From Rails version 4.2.x there is an active record method called sanitize_sql_like. So, you can do in your model a search scope like:
sanitize_sql_like
scope :search, -> search { where('"accounts"."name" LIKE ?', "#{sanitize_sql_like(search)}%") }
and call the scope like:
Account.search('Test_%')
The resulting escaped sql string is:
SELECT "accounts".* FROM "accounts" WHERE ("accounts"."name" LIKE 'Test\_\%%')
Read more here: http://edgeapi.rubyonrails.org/classes/ActiveRecord/Sanitization/ClassMethods.html
1.4m articles
1.4m replys
5 comments
57.0k users