2014-03-13 4 views
0

사이트의 카트 부분을 완성하고 싶습니다. 처음 내가 그것을 괜찮 카트에 항목을 추가 할 수 있지만 같은 항목과 두 번째 시간 나는 오류 얻을 것이다 :정의되지 않은 메소드 '+'for nil : NilClass

undefined method `+' for nil:NilClass 

Extracted source (around line #19): 

current_item = line_items.find_by_product_id(product_id) 
if current_item 
    current_item.quantity += 1 
else 
    current_item = line_items.build(product_id: product_id) 
end 

잘못 무엇입니까?

감사합니다.

답변

1

수량 필드는 데이터베이스에서 null 일 수 있습니다. 같은 뭔가 침해 줄을 변경 :

current_item.quantity = current_item.quantity.to_i + 1 
+0

작동합니다. 감사합니다. – Ziu

1

nil.to_i 반환 0

그래서 current_item.quantitynil처럼 current_item.quantity = current_item.quantity.to_i + 1

+0

수량 값이 nil이면 current_item.quantity.to_i + = 1은 오류를 반환합니다. –

1

이 보인다 사용합니다.

당신이 데이터베이스에 quantity를 저장하는 경우

... 
if current_item 
    current_item.quantity ||= 1 # sets to 1 if nil 
    current_item.quantity += 1 
else 
... 

로 기본값을 설정하려고, 다음

null: false, default: 1는 희망이 도움이 같은 마이그레이션에 추가 할 수 있습니다.

관련 문제