aboutsummaryrefslogtreecommitdiffstats
path: root/guides
diff options
context:
space:
mode:
authorLemonAndroid <gbear101010@gmail.com>2018-08-19 05:07:03 +0200
committerGitHub <noreply@github.com>2018-08-19 05:07:03 +0200
commite2589989d052da6f643081cd1eab994268d9c899 (patch)
treeed39f113fb1a65069fa18dca18c3bc4338b156ee /guides
parentdc796a0d407dfaf84abd464fc1aa2966cddb51e0 (diff)
downloadrails-e2589989d052da6f643081cd1eab994268d9c899.tar.gz
rails-e2589989d052da6f643081cd1eab994268d9c899.tar.bz2
rails-e2589989d052da6f643081cd1eab994268d9c899.zip
Explained difference between scope & class method
Diffstat (limited to 'guides')
-rw-r--r--guides/source/active_record_querying.md12
1 files changed, 9 insertions, 3 deletions
diff --git a/guides/source/active_record_querying.md b/guides/source/active_record_querying.md
index a2890b9b7a..b68b4baecf 100644
--- a/guides/source/active_record_querying.md
+++ b/guides/source/active_record_querying.md
@@ -1277,14 +1277,20 @@ class Article < ApplicationRecord
end
```
-This is exactly the same as defining a class method, and which you use is a matter of personal preference:
+This is almost the same as defining a class method, except for that scopes always return an `ActiveRecord::Relation` object.
```ruby
class Article < ApplicationRecord
- def self.published
- where(published: true)
+ scope :by_user, ()-> { where(user: user) if user }
+ def self.published_since(date)
+ where('published_at > ?', date) if date
end
end
+
+Article.by_user(nil)
+# => #<ActiveRecord::Relation []>
+Article.published_since(nil)
+# => nil
```
Scopes are also chainable within scopes: