##クラスメソッドの場合
class Book
def self.published
where(published: true)
end
end
Book.published.order(id: :desc)
#=> Attendance Load (3.8ms) SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC
nilの場合はnilが返るのでメソッドチェーンが使えない。
class Book
def self.published
nil
end
end
Book.published
#=> nil
Book.published.order(id: :desc)
#=> NoMethodError: undefined method `order' for nil:NilClass
##scopeの場合
class Book
scope :published, -> { where(published: true) }
end
Book.published.order(id: :desc)
#=> Attendance Load (3.8ms) SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC
nilの場合でもallメソッドが実行されるのでメソッドチェーンが使える。
class Book
scope :published, -> { nil }
end
Book.published
#=> nil
Book.published.order(id: :desc)
#=> Attendance Load (3.8ms) SELECT `attendances`.* FROM `attendances` WHERE `attendances`.`date` BETWEEN '2022-01-01' AND '2022-01-31' ORDER BY `attendances`.`id` DESC
##参考