-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
If you have a mongodb doc with an embedded document and the embedded doc doesn't have an _id doing assign_atributes won't update any of the embedded doc fields on the first update. Here is a summary and hack that explains it:
# mongoid requires that all embedded documents have an id. If you have existing data with embedded documents # without id's everything works fine working with the data (read only). But when updating, # an _id is generated for the embedded document each time it's created (since it doesn't exist). # Thus when the form is rendered it gets one id and when the post request is handled the id's differ. # This results in the id being set on the embedded model but none of the other attributes being saved. # The next save works fine but the first save doesn't appear to actually save anything. # # This fix (read: hack) forces the id of the embedded doc in the request to match the one we are going to update. # The resulting request will set both the attributes updated and the _id field. def accepts_nested_attributes_for(name) super class_eval <<-RUBY def assign_attributes(attrs = nil, options = {}) nested_attrs = attrs['#{name}_attributes'] if nested_attrs nested_attrs['id'] = #{name}.id.to_s end super end RUBY end