In the end, I decided to consider my own js_form_builder resource, so I have a controller that will deliver it. The controller accepts additional parameters resource_name and id. If provided, I can create an instance of the object as follows:
@object = params[:resource_name].classify.constantize.find(params[:id])
Then I just post the js.erb template which contains all my js_form_builder support. If @object was created, I can create form_for @object, then skip its attributes and create methods in the javascript form builder object that will return the inputs for each attribute using the Rails FormBuilder tags to create them.
For instance:
window.FormBuilder = function() { var builder = {}; builder.form = function() { var js = ""; js += '<%= form_for @object do |f| %>'; <% @object.attributes.each do |name, val| %> var methodName = '<%= name.camelize(:lower) %>'; <% if val.class == String %> builder[methodName] = $('<%= f.text_field name.to_sym %>'); <% end %> <% if val.class == TrueClass || val.class == FalseClass %> builder[methodName] = $('<%= f.check_box name.to_sym %> <%= f.label name.to_sym %>'); <% end %> <% end %> js += '<% end %>'; return $(js); }; builder.newForm = function() { var js = ""; js += '<%= form_for @object.class.new do |f| %>'; js += '<% end %>'; } return builder; }
Currently, I am not sure how useful this input is, since I cannot come up with a script in which I simply would not use html.erb for them. But it was sure that it made it work! :)
source share