복붙노트

[RUBY-ON-RAILS] 기록이 레일에서 컨트롤러에서 존재하는지 확인

RUBY-ON-RAILS

기록이 레일에서 컨트롤러에서 존재하는지 확인

내 응용 프로그램의 사용자는 비즈니스를 만들 수 있습니다. 그들이 내 BusinessesController I에서 색인 작업을 트리거 할 때 비즈니스가 current_user.id 관련이 있는지 확인하려면 :

나는 이것을 사용하려고 시도했다 :

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

사업이 존재하지 않는 경우에도하지만 항상 true를 돌려 ...

레코드가 내 데이터베이스에있는 경우 어떻게 테스트 할 수 있습니다?

해결법

  1. ==============================

    1.코드가 작동하지 않는 이유는 무엇입니까?

    코드가 작동하지 않는 이유는 무엇입니까?

    를 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 : .exists를 사용하십니까?

    if Business.exists?(user_id: current_user.id)
      # same as Business.where(user_id: current_user.id).exists?
      # ...
    else
      # ...
    end
    

    옵션 2 : .present를 사용하십니까? (나? .present의 반대 .blank?)

    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
    

    당신은 또한 (...) 대신 어디에요의 (current_user.id를) .find_by_user_id 사용할 수 있습니다. 첫 번째

    최선의 선택 :

  2. ==============================

    2.이 경우 나는 존재 사용하려면? 방법은 액티브 의해 제공 :

    이 경우 나는 존재 사용하려면? 방법은 액티브 의해 제공 :

    Business.exists? user_id: current_user.id
    
  3. ==============================

    3.'존재?'와 :

    '존재?'와 :

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

    '어떤?'와 :

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

    당신이 이야기 해봐 뭔가를 사용하는 경우, 범위 및 더 나은 사용과 회피 문제에 확인 .unscoped

    Business.unscoped.where(:user_id => current_user.id).any?
    
  4. ==============================

    4.액티브 :: 관계 객체 (무기 호 수 없을 것이다) 반환 액티브 번호. .empty를 사용해보십시오? 시험에 대한 관계에 어떤 레코드를 반환됩니다.

    액티브 :: 관계 객체 (무기 호 수 없을 것이다) 반환 액티브 번호. .empty를 사용해보십시오? 시험에 대한 관계에 어떤 레코드를 반환됩니다.

  5. ==============================

    5.당신이 Business.where를 호출 할 때 (: USER_ID => current_user.id) 당신은 배열을 얻을 것이다. 이 배열은 그 안에 어떤 물체 또는 하나 이상의 객체가 없을 수 있지만, null이되지 않습니다. 따라서 체크 == 전무는 진실하지 않습니다.

    당신이 Business.where를 호출 할 때 (: USER_ID => current_user.id) 당신은 배열을 얻을 것이다. 이 배열은 그 안에 어떤 물체 또는 하나 이상의 객체가 없을 수 있지만, null이되지 않습니다. 따라서 체크 == 전무는 진실하지 않습니다.

    다음을 시도 할 수 있습니다 :

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

    당신은 배열의 요소 수를 확인하고 0으로 비교 그래서.

    또는 당신은 시도 할 수 있습니다 :

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

    이것은 하나 전무를 반환합니다.

  6. ==============================

    6.

    business = Business.where(:user_id => current_user.id).first
    if business.nil?
    # no business found
    else
    # business.ceo = "me"
    end
    
  7. ==============================

    7.이 작업은 객체의 인스턴스 변수를 필요하다면 나는 이런 식으로 할 것이다 :

    이 작업은 객체의 인스턴스 변수를 필요하다면 나는 이런 식으로 할 것이다 :

    if @business = Business.where(:user_id => current_user.id).first
      #Do stuff
    else
      #Do stuff
    end
    
  8. from https://stackoverflow.com/questions/16682699/check-if-record-exists-from-controller-in-rails by cc-by-sa and MIT license