开发者

How do I do a LIKE % query in ActiveRecord?

开发者 https://www.devze.com 2023-02-21 19:35 出处:网络
I\'m trying to find开发者_如何学编程 some items that contain a certain string. If I do: MyModel.where(\"description LIKE ?\",keyword)

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?


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


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


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

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


You can use ILIKE for this

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


For PostgreSQL it will be

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

精彩评论

暂无评论...
验证码 换一张
取 消