Pregunta

I'm new to MongoID. I have following models:

class Vehicle
  include Mongoid::Document
  include Mongoid::Timestamps

  ##
  # Relationship
  embeds_one  :specification
end

class Specification
  include Mongoid::Document

  ##
  # Columns
  field :body,            type: String

  ##
  # Relationship
  embedded_in :vehicle

end

In my controller I'm trying to use $in operator in body field of specification /embed document/. How to use $in operator in embed document? I tried below code but it's not work.

result += Vehicle.where(:specification.matches => { :body.in => param(:body) }) if params[:body].present?

Thank you for help :)

¿Fue útil?

Solución

as @mu-is-too-short mentioned in his comment, to search in embedded docs you use

if params[:body].present?
  result += Vehicle.where('specification.body' => param(:body)).to_a
end

please note that Vehicle.where(...) returns a Criteria which is not the objects only the query to be evaluated.

also note that if you want to use specific operators like in, <, <= you have to use the corresponding mongodb operator for example

Vehicle.where('specification.body' => {'$in' => param(:body)})  # matches .in
Vehicle.where('specification.body' => {'$lt' => param(:body)})  # matches <
Vehicle.where('specification.body' => {'$lte' => param(:body)}) # matches <=
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top