class Bill < ActiveRecord::Base
has_many :invoices
end
class Invoice < ActiveRecord::Base
belongs_to :bill
end
然后在我的表单中,我有几个名为bill[invoice_names][]
的发票字段,因此我可以从params[:bill][:invoice_names]
访问它们。
目前我的Bill模型上有这样的方法:
#bill.rb
def save_invoices(invoices)
if invoices
invoices.each do |invoice|
@invoice = Invoice.new
@invoice.invoice = invoice
@invoice.bill_id = self.id
@invoice.save
end
end
end
然后在bill_controller的create方法上调用它,如下所示:
#bill_controller.rb
def create
@bill = Bill.new(params[:bill])
respond_to do |format|
if @bill.save
@bill.save_invoices(params[:bill][:invoice_names])
flash[:notice] = 'Bill was successfully created.'
# ...
else
# ...
end
end
end
由于rails通常是神奇的,我尝试命名字段bill[invoices][]
并交叉我的手指,希望它只是在没有额外代码的情况下同时创建这些记录。它没有用,所以我写了save_invoices
方法,并且必须将字段重命名为bill[invoices][]
以外的字段,因为这给了我一个错误。
有更好的方法吗?