I was looking for a way to run LIKE queries correctly in Ruby on Rails. But all answers suggest using string interpolation as follows:
Post.where("title LIKE ?", "%#{title}%")
Even if Arel people suggest using lowercase interpolation in the same way.
But this has a reservation. If the request contains the% character, this will affect the LIKE expression, which means that the type request 20% lesswill result in messages containing a header that contains something between 20and lessthat is not what I want. I want to get all entries containing 20% lessin the header.
I know that there is a method called sanitize_sql_likein the module ActiveRecord::Sanitization, but it is a protected method, and I cannot name it directly.
I could go to the source of the method on github and copy the code, this is actually pretty simple code:
pattern = Regexp.union(escape_character, "%", "_")
string.gsub(pattern) { |x| [escape_character, x].join }
But I wonder. If Rails already exists, why write again?
Is there a way to call a method directly? or any other way to avoid LIKE requests in Rails.
PD: In the old days in CodeIgniter, I used a method escape_like_strto do just that. I refuse to believe that Rails does not have this.
source
share