2010-05-10

my solution for rails ajax'd child-model form fields

I am mid-early development of a new interface for a web application. I can say that the interface will be making full use of as much ajax as is necessary and possible, and of course I'm using accepts_nested_attributes_for on the parent model. One problem I encountered early on was how to populate additional form fields using ajax.
The first solution I stumbled upon was the plugin ryan bates made to go along with Railscasts episode #196. This worked, but I needed something more flexible.

One of the obvious issues here is how to turn "model[childmodel_attributes][0][attribute]"(created by the form builder) into "model[childmodel_attributes][(random_number)][attribute]".
The solution is not in the documentation!

Try a random number!:
<% form_for @model do |f| %>
<% f.fields_for :childmodel, :child_index => (Time.now.usec + rand(1-999)) do |builder| %>

I use that code in my view to generate fields on a freshly built child model instance built from the rjs-calling controller.
using this method you have a more granular control over the content for the new record, a step above the model, in case you need such flexibility.

<% if builder.object.id.nil? %>
form fields here...

sorry I'm super tired, if this isn't clearly written, I don't doubt it. Actually I may make a video about my solution, because it's brilliant.