0

I'm trying to create a nested form where there is a "+" button which adds fields via jquery and ajax. I am doing it adding a step at once, so untill now I am able to add a simple text pushing the "+" button, but, as I have just said, I want to add some fields.

I have the followings:

new.html.erb

<h1>New Campaign</h1>

<%= form_for @campaign, html: { multipart: true } do |f| %>

  ....

  <div class="goods">
    <%= render "goods/good", f: f, child_index: Time.now.to_i %>
  </div>

  <div class="actions">
    <%= link_to '+', add_good_row_path(params[:campaign]=@campaign, params[:f] = f), remote: true, class: 'btn btn-large btn-success' %>
    <%= f.submit 'Crea', class: 'btn btn-large btn-warning' %>
  </div>

<% end %>

goods/_good.html.erb

<%= f.fields_for :goods, @campaign.goods.build, child_index: child_index do |good| %>

  <%= good.text_field :name, placeholder: 'Nome' %>

  <%= good.text_area :description, placeholder: 'Descrizione' %>

  <%= good.text_field :cost, placeholder: 'Costo' %>

<% end %>

campaigns_controller.rb

class CampaignsController < ApplicationController

  ....

  def add_good_row
    respond_to do |format|
      format.js
    end
  end

end

add_good_row.js.erb

$('.goods').append("hello");

I think that I understood the problem, it is to pass a f variable, a @campaign variable and a child_index to the partial, but how can I do that via jquery?

Hope I was clear...

1
  • 1
    If I understood your question correctly, this 2 part episodes of RailsCast are exactly what you are looking for. Commented Dec 13, 2013 at 16:58

1 Answer 1

1

Have a look at this gem.
I think it's what you are looking for
https://github.com/nathanvda/cocoon

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.