1

나는 다음과 같은 사용자 모델과 함께 레일 애플 리케이션을 가지고 속성 Truck 모델의 경우 primary_crew_member_idsecondary_crew_member_id이 항상 존재한다는 것을 확인하기 위해 유효성을 확인 했으므로 Truck에는 사용자/직원이 없어야합니다.레일 사용자 정의 유효성

내가 무엇을 할 수 있기를 원하는 것은 다음

  • 가 기본 또는 보조 승무원 (사용자) I가 필요로하는 검증에 확대 다른 트럭
  • 에 할당되지 않았는지 확인 트럭 A의 John Doe이 1 차 승무원 일 경우 다른 트럭의 1 차 또는 2 차 슬롯에 할당 할 수 없습니다.

검색 좀했습니다과 같은 기본 슬롯을 검증하는 검증을 마련했다 주어진 트럭에 (듀얼 rostering)를 기본 및 보조 슬롯을 모두 수행 할 수 없어야 더 홍길동 확대 그래서 :

유효성 검사 : primary_multiple_assignment

def primary_multiple_assignment 
     if Truck.has_primary(primary_crew_member_id) 
     errors.add(:base, "User has already been assigned to another truck.") 
     end 
    end 

    def self.has_primary(primary_crew_member_id) 
     primary = Truck.where(primary_crew_member_id: primary_crew_member_id).first 
     !primary.nil? 
    end 

이 작동하는 것 같다 내가 한 사용자가 하나 하나 이외의 어떤 트럭에 기본 슬롯에 지정되지 않았 음을 확인 할 수 있습니다. 그러나 위에서 언급 한대로 유효성 검사 요구 사항을 충족 할 수 있어야합니다. 그래서 기본적으로 하나의 단일 메서드에서 여러 열의 유효성을 검사하려고하지만 어떻게 작동하는지 잘 모르겠습니다.

나는 레일스 커스텀 유효성 가이드를 읽었으며 꽤 당황했다. 도움이 될만한 정보는 크게 감사하겠습니다. 그 동안 나는 해결책을 찾기 위해 땜질하고 인터넷 검색을 계속할 것입니다.

답변

0

당신은 검증 두 종류를 사용하여 그것을 할 수 있습니다 귀하의 답변에 대한

# validate that the primary or secondary crew member (user) is not assigned to 
# any other truck 
validates :primary_crew_member, uniqueness: true 
validates :secondary_crew_member, uniqueness: true 

# validate that the primary crew member can't be secondary crew member on any 
# truck (including current one) 
validate :primary_not_to_be_secondary 

# validate that the secondary crew member can't be primary crew member on any  
# truck (including current one) 
validate :secondary_not_to_be_primary 

def primary_not_to_be_secondary 
    if Truck.where(secondary_crew_member_id: primary_crew_member_id).present? 
     errors.add(:base, "Primary crew member already assigned as secondary crew member.") 
    end 
end 

def secondary_not_to_be_primary 
    if Truck.where(primary_crew_member_id: secondary_crew_member_id).present? 
     errors.add(:base, "Secondary crew member already assigned as primary crew member.") 
    end 
end 
+0

덕분에, 나는 그 때 내가 생각하지 않은 몇 가지 다른 엣지 케이스를 처리하는 때문에 내 자신의 해결책을 마련했습니다. 곧 내 대답을 게시 할 것입니다. – nulltek

관련 문제