Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Revert "Document clean chain behavior for ActiveRecord scope" #49386

Merged
merged 1 commit into from Sep 26, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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