-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
Right now I've got a backbone app returning json for a document. The json I get back is basically what I want fed directly into mongo. There is currently only 2 ways to do it and both are painful.
This first, just use the collection I get back from mongoid, convert the string ids to BSON ids and do a set:
pages = JSON.parse(params['model'])['pages'].each do |p|
p['_id'] = BSON::ObjectId(p['_id'])
p['items'].each
end
@form.collection.update(
{"_id" => BSON::ObjectId(params["id"])}, {"$set" => {"pages" => pages}})
The second way is to use accepts_nested_attributes_for for my embedded docs and convert the hash keys to be "#
{key}_attributes" and do an update_attributes on the doc:new_params = JSON.parse(params[:model])
new_params['pages'].each { |p| p['items_attributes'] = p.delete('items') }
new_params['pages_attributes'] = new_params.delete('pages')
@form.update_attributes(new_params)
The second case is shorter but doesn't really seem any cleaner. Why do I have to rename the keys to be "#{key}
_attributes"? I know that this how it works for AR but we're not dealing with relations on embedded docs. It would be nice for mongoid to be smart enough to know that I want to update my entire doc when I pass update_attributes a hash that represents the root doc containing all the subdocs.