我有以下两种模式:
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 :(得分: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