views:

72

answers:

1
class Bill < ActiveRecord::Base
  has_many :invoices
end

class Invoice < ActiveRecord::Base
  belongs_to :bill
end

Then in my form I've got several fields for invoices all with the name bill[invoice_names][] so I can access them from params[:bill][:invoice_names].

At the moment I've got a method like this on my Bill Model:

#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

And then call it on the create method of bills_controller like so:

#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

Since rails is often magical I tried naming the fields bill[invoices][] and crossed my fingers hoping it would just create those records at the same time with no extra code. It didn't work so I wrote that save_invoices method, and had to rename the fields to something other than bill[invoices][] because that gave me an error.

Is there a better way to do this?

+3  A: 

Sounds like you're looking for nested forms. Introduced in Rails 2.3, I have seen some criticism of them, so make sure you read up and weigh the options.

Ben
Yep ... thank you.
rpflo