在连接表中保存价值-Rails

时间:2018-08-16 17:40:31

标签: ruby-on-rails ruby ruby-on-rails-5

我正在尝试将金额值添加到我的联接表中。这是我的模特:

class Invoice
    has_many :invoice_payments
    has_many :payments, through: :invoice_payments
end

class InvoicePayment
    belongs_to :invoice
    belongs_to :payment
end

class Payment
    has_many :invoice_payments
    has_many :invoices, through: :invoice_payments 
end

我想将N张发票的数量与一次付款相关联。对于每个发票,我想将要支付的金额保存在联接表中。

这是我的控制器代码:

 payment = Payment.new
  if params.has_key?(:invoices)
    params[:invoices].each do |i|


        invoice = Invoice.find(i[:id])
        invoice.amount_paid = calculate_amount_paid


       payment.invoices << invoice
    end
  end

如您所见,我不确定如何在InvoicePayment表上设置金额。该字段确实存在于此表上。提前致谢。

2 个答案:

答案 0 :(得分:1)

为每张发票创建一个新的发票付款对象,并将其保存在数组中以附加付款。

payment = Payment.new

if params.has_key?(:invoices)

  invoice_payments = params[:invoices].map do |i|
    invoice = Invoice.find(i[:id])
    InvoicePayment.new(invoice: invoice, amount_paid: calculate_amount_paid)
  end

  payment.invoice_payments << invoice_payments
end

答案 1 :(得分:0)

首先,创建Payment记录,然后插入InvoicePayment记录。这样可以为您处理所需的关联。

payment = Payment.create(payment_params)
if params.has_key?(:invoices)
  params[:invoices].each do |i|
    InvoicePayment.create(invoice_id: i[:id], payment: payment, amount_paid: calculate_amount_paid)
  end
end