Mysrt
Mysrt

Reputation: 3373

Rails Nested Forms: Error when using back button and saving after deleting a record

I've noticed a problem with nested forms and i'm not sure how to solve it. My forms are working fine normally, this isn't really a question about how to get them to work. This question is more of a 'what should I do in this scenario'.

When I use a nested form via fields_for it works great. When I add in the javascript to be able to add and remove fields everything works great. I can add, save, remove, save, no problems. However If you edit an object with a nested form then delete one of the nested objects (via sending the {'_delete' => true} parameter with the object), then you use the back button and save that form again without deleting the same fields you will get an error.

Your browser caches the field that should no longer be there, then Rails tries to find the old object via the 'id' element in the hash and it fails, rightfully so. Is there anyway I can prevent this? Do I need to just manually inspect the hash to make sure the element is still there? Is there some way I can force a browser refresh or something? Thanks for your time.

Upvotes: 2

Views: 371

Answers (1)

Peter Duijnstee
Peter Duijnstee

Reputation: 3779

Yes and no. Your application has very little control over browser behavior. If the browser sends information to your application that no longer has relevance the best you can do server-side is validate against that and present the user with a clean error message (or silently drop the invalid record ids, but that could be very confusing to the user.)

The alternative is to try and get the browser to stop caching the page in question, you may have seen this before in bank or other sensitive applications where you hit your back button and you're presented with a warning "this page has expired". You could use meta tags or http headers to set the expiry date in the past or use pragma: no-cache.

Upvotes: 2

Related Questions