2013-12-16 3 views
5

nil에 대한 여러 속성을 검사하려고하는데이 게시물 simplify...을 찾았지만 원하는 결과를 얻지 못했습니다. 필요한 경우 프로필을 업데이트하려는 사용자가 있습니다. 그러나이 사용자에게는 내가 원하는 모든 데이터가 있습니다.Ruby on rails, 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 

다른 모든 단일 인스턴스가 false로 응답 할 때 왜 여기가 true로 응답합니까?

답변

9

당신이 실패하는의 .try() 체인 된 후 try(:age_id) :

그것은 @user.nil?는 # => nil
  • 경우 @user.age_id != nil # => 수익을 반환
  • 경우 @user 객체에 age_id를 호출하려고
    • a Fixnum
    • 그런 다음 Fixnum에서 try(:customer) 메서드를 호출하면 분명히 # => retur NS nil

    IRB 콘솔에서 예 :이 모든 속성이 전무 아니라는 것을 테스트하려면

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

    , 이것을 사용 :

    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

    또 다른 옵션은'% w (age_id 고객 국가) .all입니까? {| attr | @user [attr] .present? }' –