Nested Objects in Rails

In company/show.html.erb

<% form_for @company do |c| %>
    <% c.fields_for :projects do |p|%>
        <%= p.text_field :name %>
    <% end %>
   
    <%= submit_tag %>
<% end %>

Rather than a separate form for each pre-existing nested object, how do I add an extra one instead.

Let’s build a blank project in the companies_controller.rb

  def show
    @company = Company.find(params[:id])
    @company.projects.build

That solved it, I can now add a new project object to the end of the list, using the new blank project.

How do it only show the blank project and not the existing object?

This can be achieved by only adding a field for one object like the 2nd example in the following

http://apidock.com/rails/ActionView/Helpers/FormHelper/fields_for

<% form_for @company do |c| %>
    <%
    @lastProject = @company.projects.last
    c.fields_for :projects, @lastProject do |p|
    %>
            <%= p.text_field :name %>
    <% end %>
   
    <%= submit_tag %>
<% end %>

it can be further be shortened to:

<% form_for @company do |c| %>
    <% c.fields_for :projects,  @company.projects.last do |p| %>
            <%= p.text_field :name %>
    <% end %>
   
    <%= submit_tag %>
<% end %>
This entry was posted in Uncategorized by admin. Bookmark the permalink.

Comments are closed.