Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4 ActiveRecord includes(:model) without its default_scope

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!

like image 539
milkman Avatar asked Oct 10 '13 08:10

milkman


2 Answers

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)
like image 129
abstractcoder Avatar answered Oct 20 '22 09:10

abstractcoder


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
like image 3
user2503775 Avatar answered Oct 20 '22 10:10

user2503775