【问题标题】:Skip default scope for relation in mongoid跳过 mongoid 中关系的默认范围
【发布时间】: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


【解决方案1】:

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

-> { unscope(where: :column_name) } 

或者你可以使用unscoped_associations

【讨论】:

  • 这里似乎不适用于 mongoid,我需要更深入地研究它并使用它
  • 显然它只适用于has_many。我无法使用belongs_to 使其发挥作用。
  • @mohameddiaa27 已经有一段时间了,但你能解决这个问题吗?我遇到了同样的问题。
猜你喜欢
  • 1970-01-01
  • 2012-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多