how can I use like query in ruby with sinatra?

依然范特西╮ 提交于 2019-12-08 04:11:32

问题


Here's the query I tried:

@blogs = DB[:blogs].where(:title => params[:s_txt]).reverse_order(:id)

In this query, I'd like to find blogs in my database. I also need to create a query that gives users more results. How can I do this?


回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/24081696/how-can-i-use-like-query-in-ruby-with-sinatra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!