0

我有以下两个模型:

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
4

1 回答 1

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
于 2013-08-25T13:18:07.560 回答