How to use unscoped on associated relations in Rails3?

Solution 1:

Oh. I fooled myself. Thought the following would not work... but it does:

Product.unscoped do
  my_photo.product
end

Notice that you have to call unscoped on the model with the default_scope that should be bypassed.

Also, inheritance has to be respected. If you have class InsuranceProduct < Productand class FinancialProduct < Product and a default_scope in Product, all of the following two combinations will work:

InsuranceProduct.unscoped do
  my_record.insurance_products
end

FinancialProduct.unscoped do
  my_record.financial_products
end

Product.unscoped do
  my_record.products
end

However, the following will not work although the scope is defined in Product:

Product.unscoped do
  my_record.financial_products
end

I guess that's another quirk of STI in Ruby / Rails.

Solution 2:

Another option is to override the getter method and unscope super:

class Photo < ActiveRecord::Base
  belongs_to :product

  def product
    Product.unscoped{ super }
  end
end

I ran into the same situation where I had one associated model that needed to be unscoped, but in almost every other case it needed the default scope. This should save you the extra calls to unscoped if you are using the assocation getter in more than one place.