Skip to content

Commit 0e69632

Browse files
committed
Update active_record_querying.md
Added important distinction between scopes and class methods.
1 parent 2db347b commit 0e69632

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

guides/source/active_record_querying.md

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,28 @@ Using a class method is the preferred way to accept arguments for scopes. These
12961296
category.articles.created_before(time)
12971297
```
12981298

1299+
### Using conditionals
1300+
1301+
Your scope can utilize conditionals:
1302+
1303+
```ruby
1304+
class Article < ApplicationRecord
1305+
scope :created_before, ->(time) { where("created_at < ?", time) if time.present? }
1306+
end
1307+
```
1308+
1309+
Like the other examples, this will behave similarly to a class method.
1310+
1311+
```ruby
1312+
class Article < ApplicationRecord
1313+
def self.created_before(time)
1314+
where("created_at < ?", time) if time.present?
1315+
end
1316+
end
1317+
```
1318+
1319+
However, there is one important caveat: A scope will always return an `ActiveRecord::Relation` object, even if the conditional evaluates to `false`, whereas a class method, will return `nil`. This can cause `NoMethodError` when chaining class methods with conditionals, if any of the conditionals return `false`.
1320+
12991321
### Applying a default scope
13001322

13011323
If we wish for a scope to be applied across all queries to the model we can use the

0 commit comments

Comments
 (0)