Mongoid rails clear criteria

Mongoid :: Paranoia adds a default scope to a model that generates 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 that I can search for deleted and not deleted documents.

PS Model.unscoped not working

+6
source share
4 answers

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") 
+5
source

I accepted for use:

  def self.all! Mongoid::Criteria.new self end 

but self.unscoped seems to work too.

+2
source

try it

 def self.all_objects where(:deleted_at.in => [false, true]) end Model.all_objects 

UPD

the deleted_at field is a datetime field, for example the default created_at fields inserted by mongoid timestamps, so it throws an exception if checked for delete_at in [true, false], which are logical

 def self.all_objects where(:deleted_at=>{"$exists"=>false}).and(:deleted_at=>{"$exists"=>true}) end 
0
source

If someone is looking for a way to remove one of the areas from the criteria, you can do this as follows:

 query = Item.published.before(DateTime.now).unblocked query.remove_scoping(Item.before(DateTime.now)) 

After that, you can bind the criteria to the request so that it is really useful.

0
source

Source: https://habr.com/ru/post/896943/


All Articles