← Back to Upcase

accepts_nested_attributes_for and fields_for help


(Scott Hollinshead) #1

I have extracted a part of my form into a new Model called Product.

class Product < ActiveRecord::Base
  belongs_to :job_sheet
end

and this is my JobSheet model (the form)

class JobSheet < ActiveRecord::Base
  belongs_to :company
  has_many :products
  accepts_nested_attributes_for :products
end

And this is how I have the form set up.

<%= form_for([@company, @job_sheet]) do |form| %>
  <div>
    <%= form.label :address, "Installation Address" %><br>
    <%= form.text_area :address %><br>
    <%= form.label :postcode %><br>
    <%= form.text_field :postcode %>
  </div>
  ...
      <h4>Parts</h4>
    <%= form.fields_for :products do |product| %>
      <p>The following items have been allocated and need to be installed in accordance with the manuals supplied.<br>Any further items used must be entered below.</p>
      <table>
        <tr>
          <th>Product Code</th>
          <th>Product Description</th>
          <th>Alloc Qty</th>
          <th>Used</th>
          <th>Returned</th>
        </tr>
        <tr>
          <td><%= product.text_field :product_code %></td>
          <td><%= product.text_field :product_description %></td>
          <td><%= product.text_field :alloc_qty %></td>
          <td><%= product.text_field :used %></td>
          <td><%= product.text_field :returned %></td>
        </tr>
      </table>
    <% end %>
    ...
  <% end %>

But the <%= form.fields_for part is not showing up in the view, what have I done wrong?

I followed this for the fields_for and this for the nested_attributes_for I can’t seem to see what I have done wrong.


(Gergely Molnar) #2

Put this in the new method in the controller

@job_sheet.products.build

(Scott Hollinshead) #3

Thank you so much!