The search is working when I use whole words but I want also partial words to be recognized.
I have the form here:
= form_tag({}, method: :get) do
= text_field_tag :query, query, class: 'form-input search__input', placeholder: t('.placeholder')
- if query.nil?
%span.search__icon.fa.fa-search{ aria: { hidden: 'true' } }
- else
= link_to more_path do
%span.search__icon.text-success.fa.fa-times{ aria: { hidden: 'true' } }
controller:
def set_query
@query = params[:query]
end
def set_documents
@documents = @folder ? @folder.documents : current_user.documents
@documents = (params[:query] ? @documents.where(
:$text => {:$search => params[:query]}
) : @documents).page(params[:page])
end
I tried to add this in the controller to make it work as I want it:
@documents = Document.where('name LIKE ?', "%#{@query}%")
end
but then I get the error:
wrong number of arguments (given 2, expected 1)
How should I write this so that the search can work not only for whole words but also for partial words written.
If you're using mongoid, you can use regular expressions in your where
:
Document.where(name: /.*(#{@query})+.*/i)
Or try any_of
:
Document.any_of(name: /.*(#{Regexp.escape(@query)}).*/i)
So your set_documents
method should look something like:
def set_documents
@documents = @folder ? @folder.documents : current_user.documents
@documents = (params[:query] ? @documents.where(
name: /.*#{@query}.*/i
) : @documents).page(params[:page])
end
Mongoid support regular expression in queries
User.where(:name => /.*anand.*/i )
Here i for non case sensitive matching.
or
search_term = params[:search_term]
User.where({:name => Regexp.new ("/.*"+search_term+".*/") })
you can write any regular expression in reg object
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.