2013-12-16 7 views
5

Sto provando a verificare più attributi per nil, ho trovato questo post simplify... ma non sto ottenendo i risultati che voglio. Ho un utente che voglio aggiornare il loro profilo, se necessario. Questo utente ha comunque tutti i dati che voglio.Ruby on rails, controllo multiplo per attributi nil

@user.try(:age_id).nil? 
    #returns false 
    @user.try(:customer).nil? 
    #returns false 
    @user.try(:country).nil? 
    #returns false 

    @user.try(:age_id).try(:customer).try(:country).nil? 
    #returns true 

Perché è rispondere con vero qui quando tutte le altre istanze singole di tentativi risponde con falsa?

risposta

9

si concatenano il .try(), che non riesce dopo il try(:age_id):

  • Si tenta di chiamare age_id sull'oggetto @user
  • se @user.nil? # => restituisce nil
  • se @user.age_id != nil # => restituisce a Fixnum
  • Quindi si chiama il metodo try(:customer) su un Fixnum che ovviamente fallisce # => retur ns nil

ecc

Un esempio dalla console IRB:

1.9.3p448 :049 > nil.try(:nothing).try(:whatever).try(:try_this_also).nil? 
=> true 

Se si desidera verificare che tutti questi attributi non sono pari a zero, utilizzare questo:

if @user.present? 
    if @user.age_id.presence && @user.customer.presence && @user.country.presence 
    # they are all present (!= nil) 
    else 
    # there is at least one attribute missing 
    end 
end 
+14

Un'altra opzione è '% w (age_id customer country) .all? {| attr | @user [attr] .present? } ' –