Rails 4 LIKE query - ActiveRecord adds quotes

Harry Forbess picture Harry Forbess · Oct 1, 2013 · Viewed 136.3k times · Source

I am trying to do a like query like so

def self.search(search, page = 1 )
  paginate :per_page => 5, :page => page,
    :conditions => ["name LIKE '%?%' OR postal_code like '%?%'", search, search],   order => 'name'
end

But when it is run something is adding quotes which causes the sql statement to come out like so

SELECT COUNT(*)
FROM "schools" 
WHERE (name LIKE '%'havard'%' OR postal_code like '%'havard'%')):

So you can see my problem. I am using Rails 4 and Postgres 9 both of which I have never used so not sure if its and an activerecord thing or possibly a postgres thing.

How can I set this up so I have like '%my_search%' in the end query?

Answer

rb512 picture rb512 · Oct 1, 2013

Your placeholder is replaced by a string and you're not handling it right.

Replace

"name LIKE '%?%' OR postal_code LIKE '%?%'", search, search

with

"name LIKE ? OR postal_code LIKE ?", "%#{search}%", "%#{search}%"