diff options
author | LemonAndroid <gbear101010@gmail.com> | 2018-08-19 05:07:03 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-08-19 05:07:03 +0200 |
commit | e2589989d052da6f643081cd1eab994268d9c899 (patch) | |
tree | ed39f113fb1a65069fa18dca18c3bc4338b156ee /guides/source | |
parent | dc796a0d407dfaf84abd464fc1aa2966cddb51e0 (diff) | |
download | rails-e2589989d052da6f643081cd1eab994268d9c899.tar.gz rails-e2589989d052da6f643081cd1eab994268d9c899.tar.bz2 rails-e2589989d052da6f643081cd1eab994268d9c899.zip |
Explained difference between scope & class method
Diffstat (limited to 'guides/source')
-rw-r--r-- | guides/source/active_record_querying.md | 12 |
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: |