I have a code that build a form that create a model (main model) and variable number of "second" models that have a many to one relationship with the first one. The problem is with the code that manage the update (for me there are customers and many contacts that belong to them):

def edit
@customer = Customer.find(params[:id])
if params[:contacts]
params[:contacts].each_with_index do |value, index|
contact = @customer.contacts.find_or_initialize_by_id(params[:contacts][index.to_s]['id'])
if contact.new_record?
@customer.contacts.create(params[:contacts][index.to_s])
else
contact.update_attributes(params[:contacts][index.to_s])
end
end
end

if @customer.update_attributes(params[:customer])
flash[:notice] = 'Cliente aggiornato con successo'
redirect_to :action => 'index'
end
end
end


it works almost perfect but sometimes it messes it up but i don't understand why. The key here is the part that controls if the record is new record or not