2014-11-09 24 views
0

我正在嘗試處理Invoice.created的Stripe Webhook並希望保存發票行項目。我的挑戰是文件變量根據訂單項類型而改變。如何排除Rails中update_attributes的空值

我試圖導入訂單項時收到​​,因爲根據訂單項的類型,計劃對象可能爲空。

我能夠通過將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

你可以嘗試

line_item.plan.try(:name)

同樣地,對於所有的line_item.plan元素

嘗試(在軌)會給你零如果對象是零http://apidock.com/rails/Object/try

這是不是真的排除零值,但如果line_item.plan是零,那麼子值也將是nil。如果這是正確的行爲,那麼你應該嘗試try

更新:今天早上我打這個coderwall帖子(https://coderwall.com/p/wamyow),其中提到使用delegateallow_nil: true。你可以不喜歡

class InvoiceLineItem < ActiveRecord::Base 

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

    ... rest of the class ... 

end 

然後更加緊密地尋找,我不知道爲什麼你要更新所有的line_item的​​屬性,如果他們通過關係有哪些?我錯過了什麼嗎?

+0

計劃對象是來自條帶的散列的一部分。我的應用中沒有計劃模型。當您對訂閱計劃收費時,該計劃將被分段使用。如果您爲非訂購費用計費,則散列中的計劃對象爲空。現在嘗試嘗試。 – Steve 2014-11-10 00:08:04