在 Rails 4 中查找 Mongoid 中模型中文本匹配(或喜欢)的所有项目



我正在一个项目中使用 Rails 4 和 Mongodb 作为后端,由美妙的宝石"Mongoid"帮助,我想找到我的模型"项目"的所有项目,也使用"类 sql"匹配搜索词。

我的模型如下所示:

class Item
  include Mongoid::Document
  field :name, :type => String
  field :importe, :type => BigDecimal
  field :tipo, :type => String  
end

尝试在控制器中执行此操作但无法正常工作:

Item.where(name: Regexp.new(".*"+params[:keywords]+".*"))

(其中"params[关键字]"是搜索词),因为当存在具有此名称值的项目时,它不返回任何内容。

如何进行此查询?

在 ruby rails 中,我们需要使用这个:

condition = /#{params[:keywords]}/i
Item.where(:name => condition)
Item.where({:name => "/#{params[:keywords]}/i"})

这个答案是给我的,当我以后再次去这个问题时。

Item.where(name: /.*phon.*/i).to_a

最新更新