I have a student which has multiple products. Products can be selected to generate an invoice. This is the generate function:
def generate
@student = @driving_school.students.find(params[:student_id])
@products = @student.products.find(params[:product_ids])
@invoice = @driving_school.invoices.build({student_id: @student.id})
@invoice.reference = @student.full_name
@invoice.products = @products
@invoice.payment_is_due_in = 14
if @invoice.save!
redirect_to @invoice
else
redirect_to @invoice
end
end
The invoice contains lines, which are generated when creating the invoice using a before_create filter.
class Invoice < ActiveRecord::Base
...
before_create :copy_products_to_lines
...
private
def copy_products_to_lines
self.products.each do |product|
self.lines.build(
invoice_id: self.id,
description: product.name + ' ' + product.description,
amount: product.amount,
price: product.netto,
vat: true,
vat_rate: product.vat_rate,
undeletable: true
)
end
end
In rails 3.1.3 this has always worked perfectly well. Since updating to 3.1.10 because of the latest vulnerability in Rails this code broke. The invoice is generated successfully, but the lines are not created anymore. Does anyone know how come?
Adding has_many :lines, autosave: true solved it. Thanks charlysisto.