aboutsummaryrefslogtreecommitdiffstats
path: root/guides/source/active_record_querying.md
diff options
context:
space:
mode:
authorMark J. Lehman <supremebeing7@users.noreply.github.com>2016-02-10 16:00:22 -0800
committerMark J. Lehman <supremebeing7@users.noreply.github.com>2016-02-10 16:00:22 -0800
commit0e6963254abfdd2497809666a05b51906eb8697c (patch)
tree2229b9177fe7298326dc3b0e34ae6d8d2395ad47 /guides/source/active_record_querying.md
parent2db347bebc9d3f39b3c5e274b7c9beecfce73913 (diff)
downloadrails-0e6963254abfdd2497809666a05b51906eb8697c.tar.gz
rails-0e6963254abfdd2497809666a05b51906eb8697c.tar.bz2
rails-0e6963254abfdd2497809666a05b51906eb8697c.zip
Update active_record_querying.md
Added important distinction between scopes and class methods.
Diffstat (limited to 'guides/source/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