跳过mongoid中关系的默认范围

San*_*ser 1 ruby ruby-on-rails mongoid mongoid4

如何跳过mongoid中关系的默认范围?

可转移的关注点在模型上实现了软删除,并添加了以下内容

field :d_at, type: DateTime
default_scope -> { where(d_at: nil) }      
Run Code Online (Sandbox Code Playgroud)

如果一个品牌遭到破坏,我仍然希望在我加载一个引用该品牌的产品时可以使用它们这些是模型定义

class Product
  include Mongoid::Document
  field :title, type: String
  belongs_to :brand, class_name: 'Brand'
end

class Brand
  include Mongoid::Document
  include Concerns::Trashable
  field :title, type: String
end
Run Code Online (Sandbox Code Playgroud)

例:

product = Product.find([id])
puts product.brand.inspect #This brand is soft-deleted and not fetched because of the default scope
Run Code Online (Sandbox Code Playgroud)

这样可行,但它会解决更多问题

class Product
  include Mongoid::Document
  field :title, type: String
  belongs_to :brand, class_name: 'Brand'

  #unscope relation to brand
  def brand 
    Brand.unscoped.find(self.brand_id)
  end
end
Run Code Online (Sandbox Code Playgroud)

moh*_*a27 5

根据eager_loaded关联中的修复支持unscoping default_scope,您可以通过指定要在关联中忽略的列来手动跳过默认范围.

-> { unscope(where: :column_name) } 
Run Code Online (Sandbox Code Playgroud)

或者您可以使用unscoped_associations.