mirror of https://github.com/rails/rails
Revert "Document clean chain behavior for ActiveRecord scope"
This commit is contained in:
parent
4d42741a53
commit
a564341537
|
@ -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
|
||||
---------------
|
||||
|
||||
|
|
Loading…
Reference in New Issue