【问题标题】:Using dup and clone both end up modifying the record in which is was built from使用 dup 和 clone 最终都会修改从中构建的记录
【发布时间】:2016-06-11 21:50:27
【问题描述】:

我已经建立了一种机制,可以在计划更改或在当前计费周期内将用户添加到计划中时查找自动生成的发票并使用新信息对其进行更新。它比记住在一个月、一个季度、6 个月甚至一年后更改它要容易得多。这也减轻了财务部门不得不去寻找未来发票并手动更新它的负担。我希望我的代码中的cmets是清楚的。

我遇到了first_manual_invoice 的障碍。我宁愿在manual_invoice 上拨打dupclone;但是,当代码第二次或第三次运行时,未来的发票将继续除以术语频率。有什么想法可以复制这条记录吗?我不想依赖它的父级(这是我现在正在做的)。

  # Finds the upcoming / unpaid system invoice.
  manual_invoice = @subscription.manual_invoices.system.not_paid.latest.first

  # TODO: This is very hacky. If I use dup or clone on manual_invoice, and
  #   when change_plan is executed, the calculation runs, regardless if
  #   there were any updates. Also, chaining these scopes brings back all
  #   of the records when using .latest... so, I end up with an invoice
  #   where paid_at is nil.
  first_manual_invoice = @subscription.manual_invoices.system.paid.first

  # Guards changing of plan from blowing up if manual_invoice.nil?
  if manual_invoice
    subscription_term_type = @subscription.term_type
    # Iterate through the invoice's items.
    first_manual_invoice.items.each do |item|
      # Set new_amount by taking the new max_users quantity and multiply it
      #   by the previous amount. Then divide it by the previous max_users
      #   quantity. Finally, divide by payment frequency per term.
      new_amount = ((max_users.to_i * item.amount) / item.quantity)
      if subscription_term_type == 'month'
        new_amount = new_amount / 12
      elsif subscription_term_type == 'quarter'
        new_amount = new_amount / 4
      elsif subscription_term_type == 'semiannual'
        new_amount = new_amount / 2
      elsif subscription_term_type == 'annual'
        new_amount = new_amount / 1
      end

      # Update the manual_invoice items with the calcuated new_amount and
      #   user quantity.
      manual_invoice.items.first.update_attributes(quantity: max_users,
                                                   amount: new_amount)
      # Update the manual_invoice.
      manual_invoice.update_attributes(amount_in_cents: new_amount,
                                       term_type: term_type,
                                       term_start_date: term_start_date,
                                       term_end_date: term_end_date,
                                       due_on: term_end_date)
    end
  end

【问题讨论】:

    标签: ruby-on-rails ruby controller


    【解决方案1】:

    我不明白你想要什么。 但是关于重复记录,我推荐amoebagem。这对于克隆 active_record 对象很有帮助,包括关联以及关联和属性下的一些操作。

    【讨论】:

      猜你喜欢
      • 2012-09-12
      • 1970-01-01
      • 2012-02-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-16
      • 2019-06-18
      • 2021-09-30
      • 1970-01-01
      相关资源
      最近更新 更多