如何使用mongoid删除(deleted_at)字段?

时间:2021-07-20 23:12:11

I can get some data with where() method, but if some records were deleted with Paranoia delete() method (the deleted_at field is set with the date of deletion) they are not returned in the results.

我可以使用where()方法获取一些数据,但如果使用Paranoia delete()方法删除了某些记录(deleted_at字段设置了删除日期),则不会在结果中返回它们。

I can get those records using collection.deleted.entries.find() with Moped, but I need it as usual Mongoid criteria data.

我可以使用带有Moped的collection.deleted.entries.find()获取那些记录,但我需要它像往常一样使用Mongoid标准数据。

1 个解决方案

#1


1  

The paranoia plugin sets a default_scope on the model.

偏执狂插件在模型上设置default_scope。

included do
  field :deleted_at, type: Time
  class_attribute :paranoid
  self.paranoid = true

  default_scope where(deleted_at: nil)
  scope :deleted, ne(deleted_at: nil)
  define_model_callbacks :restore
end

You can tell Mongoid not to apply the default scope by using unscoped, which can be inline or take a block.

你可以告诉Mongoid不要使用unscoped来应用默认范围,这可以是内联的或者是一个块。

Band.unscoped.where(name: "Depeche Mode")
Band.unscoped do
  Band.where(name: "Depeche Mode")
end

#1


1  

The paranoia plugin sets a default_scope on the model.

偏执狂插件在模型上设置default_scope。

included do
  field :deleted_at, type: Time
  class_attribute :paranoid
  self.paranoid = true

  default_scope where(deleted_at: nil)
  scope :deleted, ne(deleted_at: nil)
  define_model_callbacks :restore
end

You can tell Mongoid not to apply the default scope by using unscoped, which can be inline or take a block.

你可以告诉Mongoid不要使用unscoped来应用默认范围,这可以是内联的或者是一个块。

Band.unscoped.where(name: "Depeche Mode")
Band.unscoped do
  Band.where(name: "Depeche Mode")
end