Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to omit existing child records in a nested form in rails?

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.

like image 336
deb Avatar asked Feb 26 '10 16:02

deb


2 Answers

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 %>
like image 98
klew Avatar answered Oct 29 '22 20:10

klew


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.

like image 29
inkdeep Avatar answered Oct 29 '22 22:10

inkdeep