【发布时间】:2014-10-22 12:53:05
【问题描述】:
如何跳过 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
【问题讨论】:
-
Product.unscoped应该返回所有产品记录而不应用任何范围 -
但这会从 Product 模型中删除默认范围,对吗?不是产品和品牌关系的范围。
-
Brand.unscoped.where(product_id: product.id)呢? -
这行得通,但这样我必须手动处理关系并更改整个代码库以检索关系,所以这不是一个选项
-
那是因为你不应该使用
default_scope: rails-bestpractices.com/posts/806-default_scope-is-evil
标签: ruby-on-rails ruby mongoid mongoid4