Dannoel
Dannoel

Reputation: 161

Rails 2 levels nested form dynamically add fields

I'm still trying to get my form working using Ryan Bates Nested_fom plugin. The problem is that I've a 2 levels nested form and when I use the f.link_to_add function it only add first level but not the second one dynamically...

When I click on the Add link, it only creates a new line for 1st level of nesting but not the 2 attached 2nd nested level ones...

For your information model is: :pinvoices has many :pinvlines (first nesting level) and :pinvlines has many :lignes (second nesting level).

Here is the code of the main form:

<%= javascript_include_tag 'javascript_pinvlines_fields_new' %>
<%= nested_form_for @pinvoice do |f| %>
<% if @pinvoice.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@pinvoice.errors.count, "error") %> prohibited this pinvoice from being saved:</h2>
<ul>
<% @pinvoice.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :contact %>
<%= f.text_field :contact, :id => 'test' %>
<%= f.label :date_facture %>
<%= f.date_select :date_facture %>
<%= f.label :montant_total %>
<%= f.text_field :montant_total %>
<br />
<br />
<div class="lignes">
<%= f.fields_for :pinvlines  %>
</div>
<%= f.link_to_add "Ajouter une ligne", :pinvlines %>
<br />
<p>
<div class="actions">
<%= f.submit %>
</div>
</p>
<% end %>

then here is the partial:

<%= f.label :description %>  
<%= f.text_field :description %>
<%= f.label :compte_id %>
<%= f.collection_select(:compte_id, @compte, :id, :nom, {:prompt => "Type de charge"}) %>
<%= f.label :quantite %>
<%= f.text_field :quantite, :class => "ip", :size => 6 %>
<%= f.label :prix_unitaire %>
<%= f.text_field :prix_unitaire, :class =>"ip", :size => 6 %>
<%= f.label :montant_HTVA %>
<%= f.text_field :montant_HTVA, :size => 6 %>
<%= f.link_to_remove "remove" %>
<p>
<%f.fields_for (:lignes) do |b|%>
<%= b.label :journal_id %><br />
<%= b.text_field :journal_id %>
<%= b.label :compte %><br />
<%= b.text_field :compte %>
<%= b.label :compte_id %><br />
<%= b.text_field :compte_id %>
<%= b.label :montant %><br />
<%= b.text_field :montant %>
</p>
<%end%>

The controller looks like:

def new
@pinvoice = Pinvoice.new
@compte = Compte.find(:all)
1.times do
pinvline = @pinvoice.pinvlines.build
2.times{pinvline.lignes.build}
end

respond_to do |format|
  format.html # new.html.erb
  format.xml  { render :xml => @pinvoice }
end
end

Is there a genius of Jquery and rails to help me with this highly tricky one... Thanks a lot.

Upvotes: 0

Views: 439

Answers (1)

Dannoel
Dannoel

Reputation: 161

Thanks guys. I've finally have done this using the old school way: form_for and fields_for

Upvotes: 1

Related Questions