1

How can I skip the default scope for relations in mongoid?

The trashable concern implements a soft-delete on the model, also it adds the following

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

If a brand gets trashed I still want to have it available when I load a product that has a reference to that brand These are the model definitions

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

Example:

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

This works, but it breaks more then it fixes

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
Sander Visser
  • 4,144
  • 1
  • 31
  • 42
  • `Product.unscoped` should return all Product records without applying any scope – MrYoshiji Oct 22 '14 at 13:09
  • But that would remove the default scope from the Product model right?. Not the scope from the relation between product and brand. – Sander Visser Oct 22 '14 at 13:13
  • What about `Brand.unscoped.where(product_id: product.id)` ? – MrYoshiji Oct 22 '14 at 13:16
  • That would work, but in that way i have to handle relations manual and change the whole codebase to retrieve relations so that isn't an option – Sander Visser Oct 22 '14 at 13:19
  • 3
    That is because you should not use `default_scope` : http://rails-bestpractices.com/posts/806-default_scope-is-evil – MrYoshiji Oct 22 '14 at 13:43
  • Still going to use the default scope because it isn't that evil in the current situation (better then writing Brand.without_deletes.all) – Sander Visser Oct 22 '14 at 15:09
  • This is the only case when using soft-deletes because you don't want to explict define that you want to load only non deleted stuff but rather the otherway arround – Sander Visser Oct 23 '14 at 09:05

1 Answers1

5

According to the the fix Support unscoping default_scope in eager_loaded associations, you can skip the default scope manually by specifying the columns to be ignored in your association.

-> { unscope(where: :column_name) } 

Or you may use unscoped_associations.

mohameddiaa27
  • 3,587
  • 1
  • 16
  • 23