0
0

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 3 years have passed since last update.

scopeでnilを返すとallが適用される

Posted at

scopeでfindfind_byfirstlastメソッドは使うべきではない

user.rb
scope :normal, -> (type) { where(type: type).first }

このようなscopeでnilを返すと、allが適用されてしまい、User.allが返ってしまう。
これを防ぐためには、scopeでは、ActiveRecord::Relationオブジェクトを返すようにする。
なので、ここでは、firstメソッドを付けずにwhereメソッドで取得する。
whereメソッドでは対象のデータない場合は、nilは返さず、[]を返す。
この[]はActiveRecord::Relationオブジェクト。

user.rb
scope :normal, -> (type) { where(type: type) }

def normal_record(type)
  normal(type).first
end

もしくは、scopeの呼び出し先で、firstメソッドを使うのもあり。
normal(type).first

参考記事

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?