rails mongoid clear criteria

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

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.



转载请标明出处:rails mongoid clear criteria
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!