Evan
Evan

Reputation: 550

Why Does ActiveRecord Scope Modify Class Scope

I have a simple class defined as follows

class User < ApplicationRecord
   
 scope :active, lambda {
   puts User.all.to_sql
   puts self.to_sql
   where(inactive: false)
 }

When I run this User.where('id = ?',1).active, then puts User.all.to_sql and puts self.to_sql both output the same sql.

"SELECT "users".* FROM "users" WHERE (id = 1)"

"SELECT "users".* FROM "users" WHERE (id = 1)"

I know I can use User.unscoped.all to remove the where clause, but why is the class level scope different in this context?

Upvotes: 0

Views: 47

Answers (1)

Evan
Evan

Reputation: 550

mu is to short helped me track this down. This is a bug that was fixed in rails 6.1.

https://guides.rubyonrails.org/6_1_release_notes.html

Named scope chain does no longer leak scope to class-level querying methods.

Upvotes: 2

Related Questions