Hey I’m trying to figure out how to convert a statement that works in mySQL into PostgreSQL and curious if anybody knows the solution.
Here is the statement that works in mySQL:
def self.by_name(keywords)
if keywords
find(:all, :conditions => ["concat(first_name," ",last_name) like?", "%#{keywords}%"])
end
end
Here is the statement that I found on this site that basically had a similar problem, but it doesn’t work for me, as in, if I do a search like Contact.by_name(“Bobby”), there are no results.
def self.by_name(keywords)
if keywords
find(:all, :conditions => ["textcat(textcat(first_name,text ' '),last_name) like?", "%#{keywords}%"])
end
end
The idea is that I could search for “Bobby”, “Fishcer”, or “Bobby Fischer” and it would match anybody with either that first name, last name, or both first and last name. Thanks!
You can use the concatenation operator (
||) to paste everything together:You’ll also notice that I switched from string interpolation,
"%#{keywords}%", to string concatenation in the SQL,'%' || ? || '%', to build the search pattern; doing this avoids injection and quoting problems. I’ve also switched toilikesince you probably want a case insensitive search.