Monday, June 25, 2007


I made a novice mistake today - tried to nest one form inside another. The functionality I was looking for is to create an entity that involves pictures. On the page where the entity gets created, I wanted to prefetch the picture specified in a text field via ajax. My initial solution was to make a standard form using rails form_for and link_to_remote. But for the life of me I could not get the link_to_remote to put the value of the text field into params. I don't think it's possible. So I just wrote my own link using prototype's Ajax.updater. The called action rendered an RJS template that made the image tag to display the picture.

But I got the weirdest result: the javascript was being rendered into the browser, instead of the result of the javascript. Thank goodness Brian put his finger on it: wrong mime type being supplied in the response. Why did that happen? Because I mixed my own ajax scripting with the rails scripting in RJS. So I converted everything to my own ajax calls. Worked fine but I'd be stuck with maintaining my own javascript for the rest of the application. Yuk.

So I backed out the ajax script and re-thought the application. My next attempt was to insert a remote_form_for. Which of course died because it creates a form nested inside my main form. HTML does not permit nested forms. Turns out rails has a helper exactly for this: submit_to_remote. It not only makes the ajax call without creating a form, it also puts each of the form fields into params for you. Problem solved.

No comments: