railsのscope
- 文字通り、そのクラスの一部のインスタンスを返します
- 意外と知られてないですが、nilを返すとallが返ります
- クラスメソッドと全く同じ挙動ではない。classメソッドはnilを返せばnilが返る
scope
[1] pry(main)> class User < ApplicationRecord
[1] pry(main)* scope :nil_scope, ->() {
[1] pry(main)* nil
[1] pry(main)* }
[1] pry(main)* end
=> :nil_scope
[2] pry(main)> User.nil_scope
User Load (4.0ms) SELECT `users`.* FROM `users`
=> [#<User id: 1, email: "xxx@gmail.com", created_at: "2018-04-14 12:05:50", updated_at: "2019-09-05 01:01:24", provider: "facebook", uid: ...]
pry(main)> User.nil_scope.size
(0.9ms) SELECT COUNT(*) FROM `users`
=> 355
class method
[1] pry(main)> class User < ApplicationRecord
[1] pry(main)* def self.nil_scope
[1] pry(main)* nil
[1] pry(main)* end
[1] pry(main)* end
=> :nil_scope
[2] pry(main)> User.nil_scope
=> nil