Mongoid:嵌入文档中的embeds_one和_destroy参数

时间:2015-08-19 18:50:55

标签: ruby-on-rails mongoid

我有这样的模特。

    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

问题是关于触发回调。当我在params之后传递给控制器​​时:

{"article"=>{"_id"=>"55d4c8a43a98c118b100001a", ... , "blocks_attributes"=>[{... "squib_attributes"=>{... "_destroy"=>1, "_id"=>"55d4ccb63a98c118b1000044"}, "_id"=>"55d4c8d73a98c118b100001c"}]}} 

嵌入式文章:: Block :: Squib不会破坏。使用embeds_many关系时没有问题。仅在embeds_one中出现问题。

如何解决?

Mongoid版本4.0.2

1 个答案:

答案 0 :(得分:0)

我在mongoid来源找到了解决方案。有代码检查embeds_one关系:

    def delete?
      destroyable? && !attributes[:id].nil?
    end

mongoid-4.0.2 / LIB / mongoid /关系/助洗剂/ nested_attributes / one.rb:82

这意味着embeds_one只能识别:id doc标识符,而不是embeds_many,它允许您使用:_ id doc标识符传递嵌入文档。

而不是:

  

{" article" => {" _id" =>" 55d4c8a43a98c118b100001a",...,   " blocks_attributes" => [{..." squib_attributes" => {..." _destroy" => 1,   "的 _id " = GT;" 55d4ccb63a98c118b1000044"},   " _id" = GT;" 55d4c8d73a98c118b100001c"}]}}

你应该通过

  

{" article" => {" _id" =>" 55d4c8a43a98c118b100001a",...,   " blocks_attributes" => [{..." squib_attributes" => {..." _destroy" => 1,   "的 ID " = GT;" 55d4ccb63a98c118b1000044"},   " _id" = GT;" 55d4c8d73a98c118b100001c"}]}}

到update_attributes方法。