ruby-on-railsrubymongodbmongoid

Find all items where match (or like) a text in a Model within Mongoid in Rails 4


I´m working in a project with Rails 4 and Mongodb as back-end helped by the wonderful gem 'Mongoid' and I want to find all items of my model 'Item' matching a search term using 'sql-like' too.

My model looks like:

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

Trying to do this in the controller but doesn´t works correctly:

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

(where "params[keywords]" is the searchterm) because doesn´t returns anything when there are items with this name value.

How do I make this query?


Solution

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