1

mongoid のリレーションのデフォルト スコープをスキップするにはどうすればよいですか?

Trashable の問題は、モデルに論理的な削除を実装し、以下を追加します。

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

修正によると、eager_loaded 関連付けで default_scope のスコープ解除をサポートするため、関連付けで無視する列を指定することで、既定のスコープを手動でスキップできます。

-> { unscope(where: :column_name) } 

または、unscoped_associationsを使用することもできます。

于 2014-11-11T18:59:03.710 に答える