Use LIKE/regex with variable in mongoid

后端 未结 5 1998
悲哀的现实
悲哀的现实 2021-02-01 18:40

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

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

H

相关标签:
5条回答
  • 2021-02-01 18:45
    searchterm = (params[:searchlogparams][:searchterm])
    @tweets = Tweet.any_of({ :text => Regexp.new ("/.*"+searchterm+".*/") })
    

    or

    searchterm = (params[:searchlogparams][:searchterm])
    @tweets = Tweet.any_of({ :text => /.*#{searchterm}.*/ })
    
    0 讨论(0)
  • 2021-02-01 18:45
    @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

    0 讨论(0)
  • 2021-02-01 18:54

    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/" 
    
    0 讨论(0)
  • 2021-02-01 19:06
    @tweets = Tweet.any_of({ :text => Regexp.new (".*"+searchterm+".*") })
    

    is ok and have result

    0 讨论(0)
  • 2021-02-01 19:06

    This worked for me by doing:

    Model.find(:all, :conditions => {:field => /regex/i})
    
    0 讨论(0)
提交回复
热议问题