1

I got a problem with nested form. My controller is:

def new
    @encomenda = Encomenda.new
    @encomenda.encomenda_produtos.build

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @encomenda }
    end
end

My view is:

<ul id="invitelist">
  <li>
  <%= f.fields_for :encomenda_produtos do |a| %>
        <%= a.label :id_produto, t("activerecord.attributes.encomenda_produto.produto", :default => "Produto"), :class => :label %>
        <%= a.collection_select :id_produto, Produto.order('nome_produto'), :id_produto, :id_produto, :class => 'collection_select_field' %>
        <br><br>
  <% end %>
  </li>
</ul>

And the Javascript is:

<script>
    $(document).ready(function() {

        $('#botao_novo_produto').click(function() {
        if ($('#invitelist li').length < 7)
            $('#invitelist li:last').clone().find('input').val('')
            .end().appendTo('#invitelist');
        else
            alert('Número máximo de produtos')
    });

        $('#botao_remove_produto').click(function() {
            if ($('#invitelist li').length > 1)
                $('#invitelist li:last').remove();
            else
                alert('Uma encomenda deve conter ao menos 1 produto.')
        });
    });
</script>

My problem here is that I need to add '@encomenda.encomenda_produtos.build' every new item (product) I added in my view. If I use something like '3.times @encomenda.encomenda_produtos.build' it works well. So, what should I do to have a dynamic form that I could add as many products I want?

Thanks all!

MMeirelles
  • 83
  • 7

2 Answers2

1

Ah, I posted an answer few days ago about something similar:

Multiple non-nested model creation on same page

With this code, no AJAX call is made and it is dynamic (you can add as many forms as you want).

Adding fields and keep only one form, one submit button:

= form_tag(url: create_user_path, remote: true) do
  %table
    %tr
      %td= text_field_tag 'user[][first_name]'
      %td= text_field_tag 'user[][last_name]'

    %tr.actions
      %td= submit_tag 'Save'
      %td= button_tag 'Add new user form', id: 'add_user_form'

    %tr.new_user_row.hidden # 'hidden' class matches the css rule: display:none;
      %td= text_field_tag "user[][last_name]"
      %td= text_field_tag "user[][last_name]"

:javascript # jQuery
  $('#add_user_form').bind('click', function(e) {
    var row = $('tr.new_user_row').clone().removeClass('hidden new_user_row');
    $('tr.actions').before(row); # will append the <tr> before the actions
  });

In UsersController:

def create
  params[:user].each do |attr|
    User.create(attr)
  end
end

Hope this helps!

Community
  • 1
  • 1
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117
0

I am a newbie and for me nested_form gem worked like butter without any headache Check out this nested_form

Sagar.Patil
  • 991
  • 8
  • 17