SQL query for field content containing whole words that begin with PHRASE
I am trying to write a SQL query to fetch rows whose fields contain multiple key words. The use for the query is to fetch results for an autocompleter function implemented with jQuery.
Right now, the autocompletion works, but my results will include every row whose content in a specific field contains the query. For example, if I type in the phrase 'ar', my results will include car, guitar , bark, etc.
I would like to return only results that begin with the phrase, as users will most li开发者_如何学运维kely not be typing in random fragments of the middle of words. I can fetch all rows where the first word begins with the query, by using Model.where((:name =~ "#{params[:q]}%")
[I am using the meta_where
gem].
However, I'd like to also return rows where the second word in the field begins with the query string, even though the first word does not.
For example, for the rows "black dog" and "dog food", the query string 'do' should return both of the rows, while the query string 'do' should not return 'undone'.
How should I write the SQL query for a search like this?
Model.where( (:name =~ "#{params[:q]}%") | (:name =~ "% #{params[:q]}%") )
This construction works with meta_where plugin only
精彩评论