2013-08-19 77 views
0

後不會被刪除,我有以下兩種模式:Mongoid embeds_many文件重裝

class Customer 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    embeds_many :locks, class_name: "Lock" 
    accepts_nested_attributes_for :locks, allow_destroy: true 

    field :name, type: String 


    validates :name, 
    presence: true 

    belongs_to :list 
end 

class Lock 
    include Mongoid::Document 
    include Mongoid::Timestamps 

    field :locked_by, type: Moped::BSON::ObjectId 

    embedded_in :customer, inverse_of: :locks, class_name: "Customer" 

    def unlock! 
    self.destroy 
    end 
end 

所以,當我嘗試刪除鎖鎖從子集刪除,但客戶的重裝後是仍然存在

locks = customer.locks.where({ some conditions}) 

locks.each do |l| 
    l.unlock! 
end 

customer.save 

where條件肯定返回正確的對象。

有人能幫助我,告訴我我做錯了什麼嗎?

更新:

這不工作也

customer.locks = [] 
customer.save 
customer.reload 

回答

0

好吧,讓我們嘗試。

首先,刪除該塊

def unlock! 
    self.destroy 
end 

然後,替換

locks = customer.locks.where({ some conditions}) 
locks.each do |l| 
     l.unlock! 
    end 

customer.locks.where({ some conditions}).delete_all 

如果它仍然不能正常工作,請在行之後添加此下一行以上

customer.locks.save