Geo
Geo

Reputation: 96837

How do I do a LIKE % query in ActiveRecord?

I'm trying to find some items that contain a certain string. If I do:

MyModel.where("description LIKE ?",keyword)

it will generate a query for an exact match. I would like to make it generate a LIKE %keyword% query. How can I do that?

Upvotes: 16

Views: 18263

Answers (5)

Minh Toàn
Minh Toàn

Reputation: 31

For PostgreSQL it will be

MyModel.where("description ILIKE ?", "%#{query}%")

Upvotes: 0

Saif Chaudhry
Saif Chaudhry

Reputation: 449

You can use ILIKE for this

MyModel.where("description ILIKE (?)", "%#{keyword}%")

Upvotes: 0

dharmjeet
dharmjeet

Reputation: 21

Model.where("name LIKE 'SH%'")

It will fetch all the name whose starting with only SH. It will work 100%. eg. SH123,SH2343

Upvotes: 1

fl00r
fl00r

Reputation: 83680

MyModel.where("description LIKE (?)", "%#{keyword}%")

Upvotes: 11

rubyprince
rubyprince

Reputation: 17793

like_keyword = "%#{keyword}%"    
MyModel.where("description LIKE ?", like_keyword)

Upvotes: 24

Related Questions