如何跳过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
答案 0 :(得分:5)
根据修复Support unscoping default_scope in eager_loaded associations,您可以通过指定要在关联中忽略的列来手动跳过默认范围。
-> { unscope(where: :column_name) }
或者您可以使用unscoped_associations。