One minute
Like operator in MongoDB 🧩
A good way to use operator LIKE
in Ruby on Rails while using MongoDB 💡
Code snippet 📌
# app/models/mongoid/base_model.rb
module Mongoid
module BaseModel
extend ActiveSupport::Concern
module ClassMethods
def _search_(k, v)
if k && v && v.size > 0
any_of({ k => /.*#{v}.*/i })
else
all
end
end
alias method :like, :_search_
end
end
end
# app/models/lead.rb
class Lead
include Mongoid::Document
include Mongoid::BaseModel # including Concern
field :first_name, type: String
end
# Rails Console
❯ Lead.like(:first_name, 'Rishi')
❯ <Mongoid::Criteria
selector: { "$or" => [{"first_name"=>/.*Rishi.*/i}]}
options: {}
class: Lead
embedded: false>
Read other posts
comments powered by Disqus