29
16

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.

ActiveRecordのscopeでnilを返すと…

Posted at

モデルのscopeを書くとき

user.rb
class User < ActiveRecord::Base
  scope :hoge, -> (fuga) { find_by(fuga: fuga) }
end

こんな風にうっかりfind_byなんかを書いてしまうと、レコードが取れない場合にnilでもUser.noneでもなくUser.all
相当のもの)がかえってくる。
こう書くべき。

user.rb
class User < ActiveRecord::Base
  def self.hoge(fuga)
    find_by(fuga: fuga)
  end
end

scopeなんてただのクラスメソッドの略記法かと思ってたけど違うんですね。

29
16
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
29
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?