user3269886
user3269886

Reputation: 47

Array of Hashes Mongoid with Rails 4

How to define a model for mongodb in rails such that a field contains array of hashes and we can easily querying inside that array list. I am using mongoid gem with Rails 4.

I just want the document should be like..

params =  { 
            "type" : String,
            "user_id" : Integer,
            "date" : Date (UTC),
            "values" : [    
                { "value": Integer, "created_at": DateTime},
                { "value": Integer, "created_at": DateTime},
                { "value": Integer, "created_at": DateTime}
            ]
        }

Thanks in Advance.

Upvotes: 1

Views: 1313

Answers (1)

vutran
vutran

Reputation: 2175

I believe that you should check out embedded document. With Mongoid and Rails:

class Something
  include Mongoid::Document

  field :type
  field :user_id, type: Integer
  field :date, type: Date

  embeds_many :values
end

class Value
  include Mongoid::Document
  include Mongoid::Timestamps::Created

  field :value, type: Integer
  embedded_in :something
end

With these two classes, Something will have many values which you can query easily. This is not actually an array of hashes but I think it would help you or at least give you an option.

Upvotes: 3

Related Questions