i have select box where on change i need to grab the value and via remote function get some field names from db and then generate those field further down the form depwning on whatoption from the select box is chosen.
The problem is is that the fields are in a f.form_for so are using the formbuilder f that has the select box in. So when i render the partial via ajax in the controller i get an error as i dont have a reference to the local form builder f.
does anyone know how or if i can get reference to the form builder orif can pass it in a remote function call and then pass into my locals in the partial ?
thanks alot, any help will be great as been stuck on this a long time!
cheers
rick
I had the same problem and my solution was to create another form builder for the same object and to pass it on to the partials.
remote_action.js.erb:
'<%= form_for(@object) do |ff| %>'
$('#some_div').html("<%= j render(partial: 'some_partial', locals: {f: ff}) %>"
'<% end %>'
It is important that the form_for tag has single quotes or else there will be javascript_escape problems.
I would simply rewrite your partial to not use the f. form helpers.
Do:
<%= text_field :object_name, :method_name %>
Instead of:
<%= f.text_field :method_name %>
I'm doing something similar to what Uri Klar suggested, but without passing the form elements as strings back to the client, since they are not needed:
# create a form helper 'f' and store it in the variable form_helper.
<% form_helper = nil %>
<% form_for @object, url: '' do |f| %>
<% form_helper = f %>
<% end %>
# pass form_helper to the form partial
$('#element').html('<%= j render "form_element", f: form_helper %>');
Notice that form_helper = nil
on the first line is there to set the scope of the variable to be beyond that of the form's block.
I think this is a better approach because it does not expose the client to any of our inner workings, but rather keeps them solely on the server side.
This snippet didn't fit well in the comments to a different answer... it helps illustrate the case where the partial is for a nested model, and is referenced in a remote method/action. It also illustrates that my literal interpretation of @object was incorrect:
'<%= form_for([@property.agency,@property]) do |parent_form| %> '
'<%= parent_form.fields_for :address do |f| %>'
$('#property_addresses').append("<%= j render(partial: 'common_partials/address', locals: {parent_form: f}) %>")
'<% end %>'
'<% end %>'
Note, that this is a @property, nested under @property.agency: where we have a fields_for nested under form_for.