1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsでscopeがnilを返すとallが返る

Posted at

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
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?