Perché il codice non funziona?
Procedimento where
restituisce un ActiveRecord :: Relation oggetto (agisce come un array che contiene i risultati della where
), può essere vuoto ma non sarà mai 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
come testare se esiste almeno un record?
Opzione 1: Uso.exists?
if Business.exists?(user_id: current_user.id)
# same as Business.where(user_id: current_user.id).exists?
# ...
else
# ...
end
Opzione 2: Utilizzo.present?
(o .blank?
, il contrario di .present?
)
if Business.where(:user_id => current_user.id).present?
# less efficiant than using .exists? (see generated SQL for .exists? vs .present?)
else
# ...
end
Opzione 3: assegnazione variabile nel if
if business = Business.where(:user_id => current_user.id).first
business.do_some_stuff
else
# do something else
end
Questa opzione può essere considerato un codice odore da parte di alcuni Linters (Rubocop per esempio).
opzione 3b: assegnazione variabile
business = Business.where(user_id: current_user.id).first
if business
# ...
else
# ...
end
È anche possibile utilizzare .find_by_user_id(current_user.id)
invece di .where(...).first
opzione migliore:
- Se non lo fai utilizzare l'oggetto
Business
(s): Opzione 1
- Se è necessario utilizzare l'oggetto
Business
(s): Opzione 3
Utilizzare 'where' restituirà un array vuoto se non ci sono record. E '[]' non è uguale a 'nil' –
Cosa ne pensi di un' meno Business.find_by_user_id (current_user.id) '? – Hengjie
possibile duplicato di [Verificare se ActiveRecord find restituisce un risultato] (http://stackoverflow.com/questions/2866473/checking-if-activerecord-find-returns-a-result) –