From e2589989d052da6f643081cd1eab994268d9c899 Mon Sep 17 00:00:00 2001 From: LemonAndroid Date: Sun, 19 Aug 2018 05:07:03 +0200 Subject: Explained difference between scope & class method --- guides/source/active_record_querying.md | 12 +++++++++--- 1 file 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) +# => # +Article.published_since(nil) +# => nil ``` Scopes are also chainable within scopes: -- cgit v1.2.3