Use LIKE/regex with variable in mongoid

Hinchy picture Hinchy · Dec 15, 2011 · Viewed 17.7k times · Source

I'm trying to find all documents whose text contains the word test. The below works fine:

@tweets = Tweet.any_of({ :text => /.*test.*/ })

However, I want to be able to search for a user supplied string. I thought the below would work but it doesn't:

searchterm = (params[:searchlogparams][:searchterm])
@tweets = Tweet.any_of({ :text => "/.*"+searchterm+".*/" })

I've tried everything I could think of, anyone know what I could do to make this work.

Thanks in advance.

Answer

Nat picture Nat · Dec 15, 2011
searchterm = (params[:searchlogparams][:searchterm])
@tweets = Tweet.any_of({ :text => Regexp.new ("/.*"+searchterm+".*/") })

or

searchterm = (params[:searchlogparams][:searchterm])
@tweets = Tweet.any_of({ :text => /.*#{searchterm}.*/ })