我正在一个项目中工作,Rails 4 和 Mongodb 作为后端,得到了美妙的 gem 'Mongoid' 的帮助,我想找到我的模型 'Item' 的所有项目也使用 'sql-like' 匹配搜索词。
我的模型看起来像:
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