1

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

可回收的关注点在模型上实现了软删除,它还​​添加了以下内容

field :d_at, type: DateTime
default_scope -> { where(d_at: nil) }      

如果一个品牌被废弃了,当我加载一个引用该品牌的产品时,我仍然希望它可用这些是模型定义

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

例子:

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

这行得通,但它破坏得更多然后它修复

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
4

1 回答 1

5

根据修复Support unscoping default_scope in eager_loaded associations,您可以通过指定关联中要忽略的列来手动跳过默认范围。

-> { unscope(where: :column_name) } 

或者您可以使用unscoped_associations

于 2014-11-11T18:59:03.710 回答