问题
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