diff options
author | Richard Schneeman <richard.schneeman+no-recruiters@gmail.com> | 2018-08-19 06:36:45 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-08-19 06:36:45 -0700 |
commit | 878800559d2639a8bea8f7e805738183bc2a7f41 (patch) | |
tree | 0e7f108c0a91db13fbd5039aff55494424fb752c | |
parent | 85a63e68881903e7f8ce5eb54b955d62b0f9ee95 (diff) | |
parent | e2589989d052da6f643081cd1eab994268d9c899 (diff) | |
download | rails-878800559d2639a8bea8f7e805738183bc2a7f41.tar.gz rails-878800559d2639a8bea8f7e805738183bc2a7f41.tar.bz2 rails-878800559d2639a8bea8f7e805738183bc2a7f41.zip |
Merge pull request #33653 from LemonAndroid/patch-1
Explained difference between scope & class method
-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: |