コードが機能しないのはなぜですか?
このwhere
メソッドはActiveRecord::Relationオブジェクト ( の結果を含む配列のように動作します) をwhere
返します。空になることはありますが、決して になることはありませんnil
。
Business.where(id: -1)
#=> returns an empty ActiveRecord::Relation ( similar to an array )
Business.where(id: -1).nil? # ( similar to == nil? )
#=> returns false
Business.where(id: -1).empty? # test if the array is empty ( similar to .blank? )
#=> returns true
少なくとも 1 つのレコードが存在するかどうかをテストする方法は?
オプション 1:使用.exists?
if Business.exists?(user_id: current_user.id)
# same as Business.where(user_id: current_user.id).exists?
# ...
else
# ...
end
オプション 2:.present?
(または.blank?
の反対.present?
)を使用する
if Business.where(:user_id => current_user.id).present?
# less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
# ...
end
オプション 3: if ステートメントでの変数の割り当て
if business = Business.where(:user_id => current_user.id).first
business.do_some_stuff
else
# do something else
end
このオプションは、一部のリンター (Rubocop など) によってコードの臭いと見なされる場合があります。
オプション 3b:変数の割り当て
business = Business.where(user_id: current_user.id).first
if business
# ...
else
# ...
end
.find_by_user_id(current_user.id)
代わりに使用することもできます.where(...).first
最良のオプション:
- オブジェクトを使用しない場合
Business
:オプション 1
- オブジェクトを使用する必要がある場合
Business
:オプション 3