Rails构建关联before_create不保存记录

时间:2013-01-11 10:05:59

标签: ruby-on-rails ruby patch

我有一个有多种产品的学生。可以选择产品来生成发票。这是生成函数:

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

发票包含使用before_create过滤器创建发票时生成的行。

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

在rails 3.1.3中,这一直非常有效。由于Rails中的最新漏洞,因此更新到3.1.10,这个代码破了。发票已成功生成,但不再创建行。有谁知道怎么来的?

1 个答案:

答案 0 :(得分:0)

添加has_many:lines,autosave:true解决了它。谢谢charlysisto。