سؤال

I want a button that will render a new nested form every time it is clicked. To do this I have used JQuery and am using Rails 3.2

On another thread someone said to use an ajax call "The onclick is executing in the browser so you're not going to be able to use erb in it. You'll want to make an ajax call (.load is a handy shortcut for this) to the server where you can render the partial using erb to get the html you need returned."

Here is my html.erb form, the form partial that is inserted at on the Jquery click and is one line, and the JQuery. The html for New Member renders correctly but the partial renders as if it was just a string.

Does anyone know how I could do an ajax call to render the partial or if I even should?

<h1>New Member</h1><%=render'new_user')%>

new.html.erb

<%= form_for(@family) do |f| %>
  <form class = 'form-horizontal' role = 'form'>
    <div class='form-group'>
      <%= f.label :name %>
      <%= f.text_field :name, placeholder: @family.name %>
    </div>
    <button type="button" id="add-family-button" class="btn btn-warning">Add to your table</button>
    <div id="child-forms-div" class='form-group'>
    </div>
    <div class='actions'>
      <%= f.submit %>
    </div>
  </form>
<% end %>

_new_user.html.erb

This is actually in one line but I could not get it formatted like that on stack overflow

<div class='form-group col-xs-3'>
  <%= f.fields_for :users, @new_user do |ff| %>
    <%= label_tag :first_name %>
    <%= ff.text_field :first_name, placeholder: 'First Name' %>
    <%= label_tag :last_name %>
    <%= ff.text_field :last_name, placeholder: 'Last Name' %>
  <% end %>
</div>

javascript.js

$("#add-family-button").click(function(){
  var form = "<h1>New Member</h1><%=render'new_user')%>";
  $("#child-forms-div").append(form);
});
هل كانت مفيدة؟

المحلول

To be able to generate nested form dynamically, you could either use ajax or javascript with some helper methods.

The process is very nicely explained in the rails cast here - rails cast link

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top