重新加载后不会删除Mongoid embeds_many文档

时间:2013-08-19 10:10:10

标签: ruby-on-rails mongodb mongoid ruby-on-rails-4 mongoid3

我有以下两种模式:

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

1 个答案:

答案 0 :(得分: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