开发者

rails mongoid clear criteria

开发者 https://www.devze.com 2023-04-04 04:43 出处:网络
Mongoid::Paranoia adds a default scope to the model which generates the criteria #<Mongoid::Criteria

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-del开发者_如何学Ceted documents.

PS Model.unscoped does not work


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")


I've taken to using:

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

but self.unscoped seems to work too.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号