Question

I am completely new to Rails and MongoDB. I am using Rails-3 and MongoDB with MongoMapper to create a small application which stores some data and returns the data in json format. The client expects the json in a particular format. But I am not able to create the same format in the saved document.

Reqd Format:

{"Name":"ABC","max":{"key":"KEY-1","value":"100"},"min":{"key":"KEY-2","value":"0"}}

Parent Doc

class Story
 include MongoMapper::Document
 key :item,     String
 key :max,      
 key :min,      
end

What I want is to create a document {"key":"KEY-1","value":"100"} first and then map that document to the parent document's max key and similarly another document to the min key.

I tried many ways, but I am not able to make it work.

Also, The I want to remove the field id (object id) from the response JSON while returning to the client. Sample JSON:

{"id":"51e64bce44ae8bf1fea3f78f","text":"Text 1","value":"Value 1"}

How can i do that?

Update Answering one of my own question : "Removing the non-required fields from the json response"

It can be done by defining the as_json method inside the Model class. This will add only the fields 'key' and 'value' to the generated json.

def as_json(options={}){
   :key  =>self.key,
   :value => self.value
}
Was it helpful?

Solution

Answering to my own question: I searched around and couldn't find any satisfactory answer for my question.

On a temporary basis, I had created hash for the inner class and was assigning the value. This was a temporary solution which is little dirty.

I had posted the same question to a mongomapper group and got the answer. Sharing that answer here..

Assume that I have a model called Inner and another called Outer

one :max, :class_name => Inner

This will embed the Inner class object to the max attribute of the Outer class

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top