Use LIKE/regex with variable in mongoid

和自甴很熟 提交于 2019-12-31 09:16:11

问题


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.


回答1:


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

or

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



回答2:


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/" 



回答3:


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

is ok and have result




回答4:


This worked for me by doing:

Model.find(:all, :conditions => {:field => /regex/i})



回答5:


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

is work, but no result

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

is ok and have result

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

is work, no result

My mongoid version is 3.1.3 and ruby version is 1.9.3



来源:https://stackoverflow.com/questions/8523111/use-like-regex-with-variable-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!