Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use LIKE/regex with variable in mongoid

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.

like image 855
Hinchy Avatar asked Dec 15 '11 16:12

Hinchy


3 Answers

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

or

searchterm = (params[:searchlogparams][:searchterm])
@tweets = Tweet.any_of({ :text => /.*#{searchterm}.*/ })
like image 55
Nat Avatar answered Nov 17 '22 15:11

Nat


There is nothing wrong with the mongodb regex query. The problem is passing variable to ruby regex string. You cannot mix string with regex like normal strings

Instead

 "/.*"+searchterm+".*/"

try this

  >>searchterm = "test"
  >>"/#{searchterm}/"
  >> "/test/" 
like image 38
RameshVel Avatar answered Nov 17 '22 14:11

RameshVel


@tweets = Tweet.any_of({ :text => Regexp.new (".*"+searchterm+".*") })

is ok and have result

like image 28
sitoto Avatar answered Nov 17 '22 15:11

sitoto