Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass form builder in remote_function in rails?

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

like image 373
richard moss Avatar asked Dec 17 '09 19:12

richard moss


3 Answers

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.

like image 92
Uri Klar Avatar answered Nov 07 '22 06:11

Uri Klar


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 %>
like image 9
MattMcKnight Avatar answered Nov 07 '22 05:11

MattMcKnight


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.

like image 4
Oded Davidov Avatar answered Nov 07 '22 06:11

Oded Davidov