Hi!
I have created a nested form and now I want to make it dynamic. I have two models, “Applications” and “Participants”. Each application may have several participants, but at least one which is the contact person. An issue that I have is that when the form is not validated it renders the participants fields twice.
- How can I avoid that?
Applications/new.html.erb
<h1>Ny anmälan</h1>
<%= semantic_form_for @application, :html => { :class => "form-horizontal" } do |f| %>
<%= f.semantic_errors %>
<%= f.inputs do %>
<%= f.inputs :for => :participants, :name => "Kontaktperson", :class => "participants_form well" do |p| %>
<%= p.input :name, :label => "Namn", :required => true %>
<%= p.input :address, :label => "Adress", :required => true %>
<%= p.input :phone, :label => "Mobiltelefon", :required => true %>
<%= p.input :email, :label => "Epostadress", :as => :email, :required => true %>
<%= p.input :age, :label => "Ålder" %>
<%= p.input :has_something, :label => "Ja..." %>
<%= p.input :special_food, :label => "Annan specialkost" %>
<%= p.input :is_contact, :as => :hidden, :value => true %>
<% end %>
<%= f.inputs :class => "participants_fields" do %>
<%= render "participant_form", :f => f %>
<% end %>
<%= link_to "<i class=\"icon-plus-sign\"> </i> Lägg till fler deltagare...".html_safe, "#", :class => "btn pull-right" %>
<%= f.inputs :name => "Övrig information" do %>
<%= f.input :extra_information, :input_html => { :class => "span4", :rows => 3 } %>
<%= f.input :membership_paid, :label => "JA" %>
<% end %>
<% end %>
<%= f.buttons do %>
<%= f.submit :value => "Skicka anmälan", :class => "btn btn-primary btn-large commit create" %>
<% end %>
<% end %>
Applications Controller
def new
@application = Application.new
@application.participants.build
respond_to do |format|
format.html
format.js { render :nothing }
end
end
def create
@application = Application.new(params[:application])
if @application.save
flash[:notice] = "Din anmälan har skickats!"
redirect_to root_path
else
flash[:error] = "Det gick inte att spara din anmälan"
render :action => "new"
end
end
I guess that my participants gets built again when it renders the new action in the “create” method. But how can I avoid that?