可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Mongoid::Paranoia adds a default scope to the model which generates the criteria
#<Mongoid::Criteria selector: {:deleted_at=>{"$exists"=>false}}, options: {}, class: Line, embedded: false>
I can find deleted documents with Model.deleted which generates,
#<Mongoid::Criteria selector: {:deleted_at=>{"$exists"=>true}}, options: {}, class: Line, embedded: false>
How can i override this so i can search both deleted and non-deleted documents.
PS Model.unscoped
does not work
回答1:
Try this(its kind of hack):
class User include Mongoid::Document include Mongoid::Paranoia def self.ignore_paranoia all.tap {|criteria| criteria.selector.delete(:deleted_at)} end end # ignore paranoia is defined on model, so can't chain it to criteria or scopes # but it returns criteria, so can chain other scope and criteria to it User.ignore_paranoia.some_scope.where(:whatever => "my_custom_value")
回答2:
I've taken to using:
def self.all! Mongoid::Criteria.new self end
but self.unscoped seems to work too.
回答3:
Try this
def self.all_objects where(:deleted_at.in => [false, true]) end Model.all_objects
UPD
the deleted_at field is a datetime field, like the default created_at fields inserted by mongoid timestamps, so it throws a exception when checked for deleted_at in [true, false] which are boolean
def self.all_objects where(:deleted_at=>{"$exists"=>false}).and(:deleted_at=>{"$exists"=>true}) end
回答4:
If someone is searching for a way to remove one of scopes from criteria you can do it like this:
query = Item.published.before(DateTime.now).unblocked query.remove_scoping(Item.before(DateTime.now))
You can chain criteria to query after that so it is really usefull.