views:

47

answers:

2

In my application an User has many Projects. I want to create a "add many projects" form, so the User can create many Projects at once.

It seemed to me that the quickest way was to make a User form with Project fields nested in it, and omit the User fields. This way when the form is submitted, the User is saved and all the new Project records are created automatically.

However, I don't want the existing Projects to show in the form. Only the empty fields for the new project that is being created (from @user.projects.build). Is there a parameter I can pass or something I can change in the form to omit the existing Project records?

<% form_for (@user) do |f| %>

   <% f.fields_for :project do |project_form| %>
      <%= render :partial => 'project', :locals => {:f => project_form}  %>
   <% end %>

   <%= add_child_link "New Project", f, :projects %>

   <%= f.submit "save" %> 

<%end%>

I'm using the Ryan Bate's complex forms example. The code works fine. I just want to omit the existing projects from showing up in this form.

A: 

You can try

  <% f.fields_for :project, Project.new do |project_form| %>
    <%= render :partial => 'project', :locals => {:f => project_form}  %>
  <% end %>

that should give you blank fields for one record.

In the controller you can generate multiple records for the relationship

 5.times { @user.projects.build }

This will make five new empty projects related to the user and your current fields_for will have fields for new records.

inkdeep
I think your answer makes perfect sense, but for some reason the fields are not being highlighted when the validation fails. I get the same problem when generating the fields without form builder. thanks!
deb
A: 

You can use new_record? method to distinguish between newly created record and old one:

<% form_for @user do |f| %>
   <% f.fields_for :project do |project_form| %>
      <%= render :partial => 'project', :locals => {:f => project_form} if project_form.object.new_record? %>
   <% end %>
   <%= add_child_link "New Project", f, :projects %>
   <%= f.submit "save" %> 
<% end %>
klew
that's exactly what I needed, thank you
deb