Skip to content

Commit

Permalink
Revert "Document clean chain behavior for ActiveRecord scope"
Browse files Browse the repository at this point in the history
  • Loading branch information
zzak committed Sep 26, 2023
1 parent 4d42741 commit a564341
Showing 1 changed file with 0 additions and 55 deletions.
55 changes: 0 additions & 55 deletions guides/source/active_record_querying.md
Expand Up @@ -2035,61 +2035,6 @@ SELECT books.* FROM books WHERE books.out_of_print = true

[`unscoped`]: https://api.rubyonrails.org/classes/ActiveRecord/Scoping/Default/ClassMethods.html#method-i-unscoped

### New Chains Inside Scope Block

Unlike class methods, [`scope`][] can easily start a new clean chain against the
model it is defined on.

```ruby
class Topic < ApplicationRecord
scope :toplevel, -> { where(parent_id: nil) }
scope :children, -> { where.not(parent_id: nil) }
scope :has_children, -> {
where(id: Topic.children.select(:parent_id))
}
end

Topic.toplevel.has_children
```

Inside `has_children` the `Topic` chain generates a subquery like this:

```sql
SELECT "topics"."parent_id" FROM "topics" WHERE "topics"."parent_id" IS NOT NULL
```

Class methods have different behavior which can be surprising if you expect them
to work exactly like scopes.

```ruby
class Topic < ApplicationRecord
def self.toplevel
where(parent_id: nil)
end

def self.children
where.not(parent_id: nil)
end

def self.has_children
where(id: Topic.children.select(:parent_id))
end
end

Topic.toplevel.has_children
```

`Topic` inside `has_children` will implicitly include `toplevel` from the outer
chain resulting in a subquery of:

```sql
SELECT "topics"."parent_id" FROM "topics" WHERE "topics"."parent_id" IS NULL AND "topics"."parent_id" IS NOT NULL
```

NOTE: In class methods, `self` refers back to the model. In scope, `self` acts as
a chained relation. For the example above, `self` and `Topic` are interchangeable
within the class method definition.

Dynamic Finders
---------------

Expand Down

0 comments on commit a564341

Please sign in to comment.