Home > OS >  How to escape special charaters like % on ilike in rails
How to escape special charaters like % on ilike in rails

Time:09-24

How to escape the special characters such as %, & using ilike in rails

As i'm getting error when i enter special characters like %,& in search box , as my query was this book.where("book.name ilike ?", "%#{options[:book_name]}%")

How to escape the special characters using ilike?

CodePudding user response:

You can sanitize your query with sanitize_sql_like:

book.where("book.name ILIKE ?", "%#{sanitize_sql_like(options[:book_name])}%")

CodePudding user response:

This can be accomplished with .gsub and a regexp.

options = { book_name: '%Hello & W%orld!' }
options[:book_name].gsub(/[%&]/, '')
#=> "Hello  World!"

The full solution is as follows:

book.where("book.name ILIKE ?", "%#{options[:book_name].sub(/[%&]/, '')}%")
  • Related