2014-11-09 2 views
0

Invoice.created 용 Stripe Webhook을 처리하려고하고 송장 행 항목을 저장하려고합니다. 필자의 과제는 파일 변수가 광고 항목 유형에 따라 변경된다는 것입니다.레일에서 update_attributes에서 Null 값을 제외하는 방법

광고 항목의 유형에 따라 계획 개체가 null 일 수 있으므로 광고 항목 가져 오기를 시도 할 때 undefined method 'name' for nil:NilClass가 표시됩니다.

update_attributes를 2로 분리하여 문제를 해결할 수 있었지만 계획 개체가있는 경우에만 문제가 발생했습니다. 다음은 내가 일하기 위해 얻은 것입니다. 내 희망은 더 좋은 방법이 있다는 것입니다.

@invoice_line_item = InvoiceLineItem.where(stripe_line_item_id: line_item.id).first_or_create(invoice_id: @invoice.id) 
    @invoice_line_item.update_attributes(
    amount: line_item.amount, 
    currency: line_item.currency, 
    period_start: Time.at(line_item.period.start).strftime("%m-%d-%Y"), 
    period_end: Time.at(line_item.period.end).strftime("%m-%d-%Y"), 
    proration: line_item.proration, 
    item_type: line_item.type) 
    if line_item.plan.present? 
    @invoice_line_item.update_attributes(
     plan_name: line_item.plan.name, 
     plan_interval: line_item.plan.interval, 
     plan_amount: line_item.plan.amount, 
     trial_period_days: line_item.plan.trial_period_days) 
    end 

답변

0

당신은 당신이 그것의

http://apidock.com/rails/Object/try 전무 주제 인 경우 nil을 줄 것이다 모든 line_item.plan 요소 (레일)

시도를 유사하게

line_item.plan.try(:name)

등을 시도 할 수 실제로는 nil 값을 제외하지 않지만, line_item.plan이 0이면 서브 또한 값은 nil이됩니다. 그것이 올바른 행동이라면 try을 시도해야합니다.

업데이트 : delegateallow_nil: true의 사용에 대해 언급 한 오늘 아침 ()의이 코더 월 게시판을 방문했습니다. 당신은 그런 다음 line_item의 모든 plan 속성을 업데이트하고 왜이 관계를 통해 사용할 수 있는지 궁금, 더 자세히보고

class InvoiceLineItem < ActiveRecord::Base 

    delegate :name, :interval, :amount, :trial_period_days, to: :plan, allow_nil: true 

    ... rest of the class ... 

end 

같은 일을 할 수 있을까? 내가 놓친 게 있니?

+0

계획 개체는 스트라이프에서 오는 해시의 일부입니다. 내 앱에 계획 모델이 없습니다. 이 요금제는 구독 요금을 청구 할 때 스트라이프에서 사용됩니다. 비 구독 요금 청구를하면 해시의 계획 개체가 null입니다. 시도해보기. – Steve

관련 문제