I have the following situation in my Rails app. There are two models, let's say User and Company:
class User < ActiveRecord::Base
  belongs_to :company
  default_scope -> {where(removed_at: nil)}
end
and
class Company < ActiveRecord::Base
  has_many :users
end
What I want now is loading an Company record and include the Users
Company.unscoped.all.includes(:users)
What will result in a query to the users table which includes the default-scope. So I get the Company record with all not removed users prefetched. But in this case I do also want the Users where removed_at is not null (=> the removed User records). The "unscoped" method is only applied to the Company model, not to the User model.
Is there any way to do this? Thanks for any ideas!
Here is the solution I got working in my Rails 4.0 application
class User < ActiveRecord::Base
  belongs_to :company
  default_scope -> {where(removed_at: nil)}
end
class UserUnscoped < User
  self.default_scopes = []
end
class Company < ActiveRecord::Base
  has_many :users, class_name: "UserUnscoped"
end
Company.unscoped.all.includes(:users)
                        This method accepts a block. All queries inside the block will not use the default_scope:
User.unscoped { Company.includes(:users).all }
or:
User.unscoped do
 Company.includes(:users).all
end
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With