Dlaczego twój kod nie działa?
Sposób where
zwraca ActiveRecord :: Relacja przedmiotu (działa jak tablica, która zawiera wyniki where
) może być pusty, ale to nigdy nie będzie 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
Jak sprawdzić, czy przynajmniej jeden rekord istnieje?
Opcja 1: Stosując .exists?
if Business.exists?(user_id: current_user.id)
# same as Business.where(user_id: current_user.id).exists?
# ...
else
# ...
end
Opcja 2: za pomocą .present?
(lub .blank?
, przeciwny .present?
)
if Business.where(:user_id => current_user.id).present?
# less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
# ...
end
Wariant 3: wybór zmiennej w if
if business = Business.where(:user_id => current_user.id).first
business.do_some_stuff
else
# do something else
end
Opcja ta może być uznana za zapach kod niektórych linters (Rubocop na przykład).
Wariant 3b: przypisanie zmiennej
business = Business.where(user_id: current_user.id).first
if business
# ...
else
# ...
end
Można również użyć .find_by_user_id(current_user.id)
zamiast .where(...).first
najlepszym rozwiązaniem:
- Jeśli nie użyć obiektu
Business
(s): Wariant 1
- Jeśli trzeba użyć obiektu
Business
(s): Option 3
Używanie 'where' zwraca pustą tablicę, jeśli nie ma rekordów. I '[]' nie równa 'nil' –
Co powiesz na' chyba Business.find_by_user_id (current_user.id) '? – Hengjie
możliwy duplikat [Sprawdzanie, czy ActiveRecord find zwraca wynik] (http://stackoverflow.com/questions/2866473/checking-if-activerecord-find-returns-a-result) –