Lost of form data on validation error

Hello,

I’ve been looking for a solution to this problem for days and I haven’t
been able to find anything quite relevant so I hope you guys can help
:).

RoR takes care of everything when submitting a form and redisplaying the
entered data in case of an error (i.e. scaffold methods). This works
fine for one record.

However this does not seem that obvious to extend to multiple records in
one single form.
I’ve managed to go as far as creating all the records (safely saved to
the DB) and I’m also able to edit them.

But my problem comes when I’ve got a validation error in my form. I
manage to display the relevant error message but all correct submitted
fields are now blank.

In short, here is what I do in my controller (I’ve modified/shortened
for the sake of the forum):

def save_multiple_records

create an array which holds multiple records

@records_array = Array.new
10.times do
@records_array << Record.new
end

if request.post?
# Update @records_array with submitted data
@records_array.collect! do |record|
record = Record.new(params[“record_#{id}”])
end

 # Then if one of the record is not valid I render the same action
 if !all_valid
   render :action => "save_multiple_records"
 end

end
end

In my view, I loop through @records_array and create the form fields
with a unique id for each record so I can then get it back correctly in
the controller as shown above.
As I said before, this mechanism is ok as I manage to save all records
when everything is ok.

Now, I would have thought that @records_array would persist on an error
and that the looping that happens in my view would now be done on the
updated array and therefore redisplay the entered data (it works for one
record, i.e. scaffold!).

Or is it that the piece of code before the if request.post? will be run
again on the render and therefore erase all the data? Again this works
for the scaffold! Or there is something I’m missing!

So my question is: what is the RoR way to handle multiple records like
this?

Thanks!

I don’t know how ROR way to handle multiple records, but I have same
issue with you. I have custom input. In my view, for one input, I have
four radio buttons and each of them is accompanied by text field. If
the validation gives error, the radio button is still on but the text
field will be empty. The solution? I use a bunch javascript in the view
(off course I put the detail of function in controller helper) to
update the text field.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs