-
Type: Task
-
Resolution: Done
-
Affects Version/s: None
-
Component/s: None
We are using the current version of Mongoid master and experience two problems when using nested attributes:
[1] Callbacks are only called for the first embedded document.
[2] If the embedded document id is generated in 'before_create' we need to do a reload to see the correct id field.
This was working on master three days ago, but it is not working now.
class Event include Mongoid::Document include Mongoid::Timestamps embeds_many :cache_products, :cascade_callbacks => true accepts_nested_attributes_for :cache_products, :allow_destroy => true end class CacheProduct include Mongoid::Document include Mongoid::Timestamps field :product_id, :type => Integer field :random_num, :type => Integer field :_id, :type => Integer, default: ->{ product_id } field :product_name, :type => String, :default => "" embedded_in :event before_create :create_product def create_product self.product_id = Random.rand(10000000000).to_i end end
When running the following command:
ev = Event.create( "cache_products_attributes"=>{"0"=>{"product_name"=>"fdsafsa", "_destroy"=>"false"}, "new_1340722741513"=>{"product_name"=>"fdafsdfaf", "_destroy"=>"false"}})
The first embedded document does not have a proper id set until 'ev.reload' is called. The last document still has no values for field that should be generated in callbacks:
ev.cache_products.first.to_json => "{\"_id\":null,\"created_at\":\"2012-06-26T16:01:06Z\",\"product_id\":2125870922,\"product_name\":\"fdsafsa\",\"random_num\":null,\"updated_at\":\"2012-06-26T16:01:06Z\"}" ev.cache_products.last.to_json => "{\"_id\":null,\"created_at\":null,\"product_id\":null,\"product_name\":\"fdafsdfaf\",\"random_num\":null,\"updated_at\":null}"
A reload populates the id for the first embedded document, but does not fix the problems on the last document:
ev.reload ev.cache_products.first.to_json => "{\"_id\":2125870922,\"created_at\":\"2012-06-26T16:01:06Z\",\"product_id\":2125870922,\"product_name\":\"fdsafsa\",\"random_num\":null,\"updated_at\":\"2012-06-26T16:01:06Z\"}" ev.cache_products.last.to_json => "{\"_id\":null,\"created_at\":null,\"product_id\":null,\"product_name\":\"fdafsdfaf\",\"random_num\":null,\"updated_at\":null}"