Reputation: 981
I have such model.
class Article
include Mongoid::Document
embeds_many :blocks, class_name: 'Article::Block', cascade_callbacks: true
accepts_nested_attributes_for :blocks, allow_destroy: true
...
class Block
include Mongoid::Document
embedded_in :article
embeds_one :squib, class_name:'Article::Block::Squib', cascade_callbacks: true
accepts_nested_attributes_for :squib, allow_destroy: true
...
class Squib
include Mongoid::Document
...
embedded_in :block, class_name: 'Article::Block'
end
end
end
problem is about firing callbacks. When I pass to controller following params:
{"article"=>{"_id"=>"55d4c8a43a98c118b100001a", ... , "blocks_attributes"=>[{... "squib_attributes"=>{... "_destroy"=>1, "_id"=>"55d4ccb63a98c118b1000044"}, "_id"=>"55d4c8d73a98c118b100001c"}]}}
Embedded Article::Block::Squib doesn't destroys. There is no problem when I am using embeds_many relation. Problem only in embeds_one.
How to fix it?
Mongoid version 4.0.2
Upvotes: 0
Views: 342
Reputation: 981
I found solution at mongoid sources. There is code with check for embeds_one relation:
def delete?
destroyable? && !attributes[:id].nil?
end
mongoid-4.0.2/lib/mongoid/relations/builders/nested_attributes/one.rb:82
It means that embeds_one understands only :id doc identifier,instead of embeds_many, that allow you to pass embedded documents with :_id doc identifier.
Instead of:
{"article"=>{"_id"=>"55d4c8a43a98c118b100001a", ... , "blocks_attributes"=>[{... "squib_attributes"=>{... "_destroy"=>1, "_id"=>"55d4ccb63a98c118b1000044"}, "_id"=>"55d4c8d73a98c118b100001c"}]}}
you should pass
{"article"=>{"_id"=>"55d4c8a43a98c118b100001a", ... , "blocks_attributes"=>[{... "squib_attributes"=>{... "_destroy"=>1, "id"=>"55d4ccb63a98c118b1000044"}, "_id"=>"55d4c8d73a98c118b100001c"}]}}
to update_attributes method.
Upvotes: 1