Question

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 likely 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?

Was it helpful?

Solution

Model.where( (:name =~ "#{params[:q]}%") | (:name =~ "% #{params[:q]}%") )

This construction works with meta_where plugin only

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top