97

私のアプリでは、ユーザーはビジネスを作成できます。index彼らが私のアクションをトリガーするときBusinessesController、ビジネスが次のものに関連しているかどうかを確認したいcurrent_user.id:

  • はいの場合: ビジネスを表示します。
  • いいえの場合: アクションにリダイレクトしnewます。

私はこれを使用しようとしていました:

if Business.where(:user_id => current_user.id) == nil
  # no business found
end

しかし、ビジネスが存在しない場合でも、常に true を返します...

データベースにレコードが存在するかどうかをテストするにはどうすればよいですか?

4

7 に答える 7

247

コードが機能しないのはなぜですか?

この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
于 2013-05-22T02:53:00.380 に答える
29

この場合exists?、ActiveRecord が提供するメソッドを使用したいと思います。

Business.exists? user_id: current_user.id
于 2013-06-26T17:34:08.183 に答える
5

「存在しますか?」:

Business.exists? user_id: current_user.id #=> 1 or nil

「何か?」で:

Business.where(:user_id => current_user.id).any? #=> true or false

.where で何かを使用する場合は、スコープに関する問題を回避し、.unscoped を使用することをお勧めし ます

Business.unscoped.where(:user_id => current_user.id).any?
于 2013-08-21T09:39:19.203 に答える
1

ActiveRecord#where は ActiveRecord::Relation オブジェクトを返します (nil になることはありません)。.empty を使用してみてください。レコードを返すかどうかをテストする関係について。

于 2013-05-22T03:01:37.607 に答える
1

呼び出すBusiness.where(:user_id => current_user.id)と、配列が取得されます。この配列には、オブジェクトが含まれていないか、1 つまたは複数のオブジェクトが含まれている可能性がありますが、null にはなりません。したがって、check == nil が true になることはありません。

次のことを試すことができます。

if Business.where(:user_id => current_user.id).count == 0

したがって、配列内の要素の数を確認し、それらをゼロと比較します。

またはあなたが試すことができます:

if Business.find_by_user_id(current_user.id).nil?

これは 1 または nil を返します。

于 2013-05-22T03:07:09.003 に答える
1
business = Business.where(:user_id => current_user.id).first
if business.nil?
# no business found
else
# business.ceo = "me"
end
于 2015-03-19T11:06:08.543 に答える