pass form builder in remote_function in rails?

自闭症网瘾萝莉.ら 提交于 2019-12-04 05:02:42
Uri Klar

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!