Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: simple wildcard search from console

What's the easiest way to do a quick wildcard search on a field from the console? I don't care against guarding against SQL injection.

I'm using PostgreSQL.

Searching for title with strings containing "emerging'

This works but is somewhat cumbersome. Curious if there was a shorthand?

Product.where("title @@ :q", q: "emerging")

Equally cumbersome but no longer appear to work for me in Rails 4:

Product.where("title ILIKE ?", "emerging")
Product.where("title ilike :q", q: "emerging")

I guess I'm looking for something like Product.where(title: "*emerging*")

like image 695
Meltemi Avatar asked Oct 25 '13 15:10

Meltemi


2 Answers

This should do it:

word = 'emerging'
Product.where('title ILIKE ?', "%#{word}%")
  • The ILIKE makes the search not sensitive to the case (PostgreSQL feature!)
  • the "%" wildcard makes the search match every product having a title containing "word" inside with (or without) stuff before and/or after.
like image 133
MrYoshiji Avatar answered Nov 08 '22 20:11

MrYoshiji


Use LIKE, like this:

Product.where('title LIKE ?', '%emerging%')
like image 26
Christian Fazzini Avatar answered Nov 08 '22 20:11

Christian Fazzini