aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJon Moss <maclover7@users.noreply.github.com>2016-02-10 19:12:19 -0500
committerJon Moss <maclover7@users.noreply.github.com>2016-02-10 19:12:19 -0500
commit270e25ce851126c5a14cd51e97b0201aa8ac0b59 (patch)
treecba9d7cc4425b69ba5c25cf3dc5319dc66bad801
parentab4708c9a25fb2a113a9c95697055fd79cdfc63a (diff)
parent0e6963254abfdd2497809666a05b51906eb8697c (diff)
downloadrails-270e25ce851126c5a14cd51e97b0201aa8ac0b59.tar.gz
rails-270e25ce851126c5a14cd51e97b0201aa8ac0b59.tar.bz2
rails-270e25ce851126c5a14cd51e97b0201aa8ac0b59.zip
Merge pull request #23606 from supremebeing7/patch-1
Update active_record_querying.md
-rw-r--r--guides/source/active_record_querying.md22
1 files changed, 22 insertions, 0 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index 63658e7c8b..1235c04c50 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -1296,6 +1296,28 @@ Using a class method is the preferred way to accept arguments for scopes. These
category.articles.created_before(time)
```
+### Using conditionals
+
+Your scope can utilize conditionals:
+
+```ruby
+class Article < ApplicationRecord
+ scope :created_before, ->(time) { where("created_at < ?", time) if time.present? }
+end
+```
+
+Like the other examples, this will behave similarly to a class method.
+
+```ruby
+class Article < ApplicationRecord
+ def self.created_before(time)
+ where("created_at < ?", time) if time.present?
+ end
+end
+```
+
+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`.
+
### Applying a default scope
If we wish for a scope to be applied across all queries to the model we can use the