how can I use like query in ruby with sinatra?

爱⌒轻易说出口 提交于 2019-12-06 15:06:41

I also had this problem and only found this solution

@blogs = DB[:blogs].where("title LIKE '%#{params[:s_txt]}%'").reverse_order(:id)

Curious if there are better ways..

Searching in two fields is repeating the LIKE and seperating by AND or OR

@blogs = DB[:blogs].where("title LIKE '%#{params[:s_txt]}%' 
  or comment LIKE '%#{params[:c_txt]}%'").reverse_order(:id)

or do it like this

@blogs = DB[:blogs].where("title||comment LIKE '%#{params[:s_txt]}%'").reverse_order(:id)

Tested in Sqlite and it works. One advise: in lage tables you 'd better drop the first % if possible because the database will do a full table scan otherwise without using indexes but you can find all that stuff in the sql questions.

It is better to use dynamic parameters to avoid SQL injection:

@blogs = DB[:blogs].where("title LIKE ?", "%#{params[:s_txt]}%").reverse_order(:id)

or

@blogs = DB[:blogs].where("title LIKE :text", text: "%#{params[:s_txt]}%").reverse_order(:id)

You can easily add more parameters to this:

@blogs = DB[:blogs].where("title LIKE ? OR content LIKE ?", "%#{params[:s_txt]}%", "%#{params[:s_txt]}%").reverse_order(:id)

or

@blogs = DB[:blogs].where("title LIKE :text OR content LIKE :text", text: "%#{params[:s_txt]}%").reverse_order(:id)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!