Today I wanted to RESTfully create/edit Rails resource records using jQuery. My initial impulse was to simply $.post(url, jsonObject, callback, "json"). This was wrong because I didn't RTFM the first time.
So after trying out the various ways I could tell Rails that I want to use JSON as my content type for RESTfully creating/editing resource records, including $.ajax({...,contentType: "application/json; char-set...", ...}), $.post(url, jsonObject, f(), "json"). I almost gave up and resorted to post a "stringified" JSON object, which involved adding a JSON.decode in the controller's create/update actions.
Then after crying into my afternoon coffee about how I broke Rails convention and wondering why I couldn't have a HashWithIndifferentAccess built for me too. I remembered puzzling over the funny names rails generates for its form elements (e.g. person[id], person[first_name], etc....) the first time I seen them. Then BAM I realized its not so magical after all the HashWithIndifferentAccess is built and.... POOF... magically appears in params by HTTP putting these peculiarly-named-name-value pairs like so:
[{name: "person[id]", value: "1"}, {name: "person[first_name]"},... ]
So while it would be great if I could simply build JSON objects and then HTTP PUT them to Rails, it turns out that building the JSON object is an unnecessary extra step (in my case), since all the information was sitting right there on the page (I needed to create nested model records based on a particular configuration of related models) distributed across some form elements.
(Before posting my code, note that I have not tested cross browser compatibility and that I am using Rails 2.2.2 and jQuery HEAD.)
$.post(url, $.(".particular_set_of_form_controls").serializeArray(), callback, "json");
In the case where data for creating a model is not actually stored on the page and all you have is a JSON object then a JSON method for serializing into an array like the one above may be used. Someone must have one... I'll update this if I find one... or write my own (if I get desperate)...
Friday, June 12, 2009
Subscribe to:
Posts (Atom)