我有轨道模型,如:
Class Invoice < ApplicationRecord
has_many :invoicepayements
has_many :payements, through: :invoicepayements
end
Class Payement < ApplicationRecord
has_many :invoicepayements
has_many :invoices, through: :invoicepayements
end
class InvoicePayement < ApplicationRecord
belongs_to :payement
belongs_to :invoice
end
3个模型具有以下属性:
Invoice: total
Payement: total, remain
InvoicePayement: used
在我的应用中首先创建@payement
,之后创建@invoice
多选到Payement,当创建新的payement时,剩余等于total(由用户输入)和当创建新的Invoice时,我希望它从相关的payement计算剩余的值,并将使用的值存储在InvoicePayement中使用的attr中。如果rails允许我这样做?如果是的话怎么样?
答案 0 :(得分:0)
我终于发现我的错误在哪里,我试图应用(胖模型,瘦控制器)的原则我创建了一个Invoice方法来计算保留在Payement中并在InvoicePayement中使用它并不起作用,我决定在这里创建控制器的代码:
respond_to do |format|
if @invoice.save
total = @invoice.total
@invoice.payements.each do |payement|
if (total > 0) && (payement.remain > 0)
if payement.remain >= total
invoicepayement = payement.invoicepayements.new(used: total, invoice_id: @invoice.id, payement_id: payement.id)
invoicepayement.save
payement.remain = payement.remain - total
total = 0
payement.save
elsif payement.remain < total
total = total - payement.remain
invoicepayement = payement.invoicepayements.new(used: payement.remain, invoice_id: @invoice.id, payement_id: payement.id)
invoicepayement.save
payement.remain = 0
payement.save
end
end
end
format.html { redirect_to @invoice, notice: 'Receipt was successfully created.' }
format.json { render :show, status: :created, location: @invoice }
else
format.html { render :new }
format.json { render json: @invoice.errors, status: :unprocessable_entity }
end
end
end
但现在我想提高性能,任何建议我应该如何使用此代码进行交易?