I have an array with some parameters dynamically generated in Javascript. After filling some fields and pressing submit I want to generate multiple records in DB which contains data from form field + data from the array i.e. name,array[0];name,array[1];name,array[2] etc.. So I've decided to do following: in my view (I use simpleform)
<%= simple_form_for(@stop_time, :html => {:remote => true, :class => 'well form-horizontal'}) do |f| %>
<%= f.input :stop_id %>
<%= f.button :submit %>
and the script part (I use fixed values for now):
<script type="text/javascript">
$('#new_stop_time').submit(function(){
$.ajax({
beforeSend: function(xhr) {
xhr.setRequestHeader(
'X-CSRF-Token',
$('meta[name="csrf-token"]').attr('content'))},
url: "/stop_times.json",
type: "POST",
contentType: "application/json",
data: JSON.stringify([
arrival_time:"04:40:00",
created_at:"2013-04-20T20:37:30Z",
departure_time:"04:40:00",
drop_off_type:0,
id:1881,
pickup_type:0,
shape_dist_traveled:null,
stop_headsign:null,
stop_id:84612,
stop_sequence:1,
trip_id:"ABCDE",
updated_at:"2013-04-20T20:37:30Z"
]
]})
});
});
but in chrome debug I see 2 POST requests being sent (one /stoptimes from form and other /stop_times.json wich got response with code 422).
Shouldn't be just one POST request? I want Javascript to do POST not the form. Is there any other (more obvious) way to create multiple records?
Thanks,
Dominik
Thanks @UberNeet:) Now it works with one record. It passes to the controller and the correct record is created. I can create the whole array to pass it as JSON but not sure how to handle it on controller's side. I assume there's some loop needed but I don't know how the params is build.I've added following:
@i = 0
while @i< params.length-1 do
@stop_time = StopTime.new(params[@i][:stop_time])
@i +=1
end