Sasha
Sasha

Reputation: 6466

Nested forms in rails for existing objects

In my app, I have a page where I want admin users to be able to update a particular characteristic of my "Package" model, which belongs to both the "Order" model and the "Item" model. It's a little complicated, but I basically want to present in a table all of the Packages belonging to a given Item, ordered in a particular way (that's what my packages_for_log method below does), with two blanks for updating the weight of the item. All the updates should ideally be submitted at once, with a single submit button at the bottom of the page. I've attempted a whole bunch of solutions, and my current one is below, but gives this error when I visit the page in my server:

undefined method `actual_lbs' for #<ActionView::Helpers::FormBuilder:0x007ff67df6c9c8>

The error's confusing to me, cause I was hoping that I was calling that method on the package instance, not a helper. Bit confused. At any rate, my code is below. The relevant section of the view:

<% form_for(@item) do |a| %>
  <% @item.packages_for_log.each do |p| %>
    <%= a.fields_for p do |i| %>
     <tr>
        <td><%= p.order.name %></td>
        <td><%= p.order.processed_notes %></td>
      <% if p.order.user %>
        <td><%= "#{p.order.user.name.first(3).upcase}-#{p.id}" %></td>
      <% else %>
        <td><%= p.order.id %></td>
      <% end %>
        <td>
          <%= i.text_field :actual_lbs %>
        </td>
        <td>
          <%= i.text_field :actual_oz %>
        </td>
          <%= i.hidden_field :true_weight, value: (i.actual_lbs + i.actual_oz/16) %>
     </tr>
    <% end %>
  <% end %>
<% end %>

Relevant section of the package.rb model file:

 attr_accessible :order_id, :price, :true_weight, :actual_lbs, :actual_oz
 attr_accessor :actual_lbs, :actual_oz  # These two are virtual attributes for the above calc

And I added resources :packages to my routes file.

Any idea what I'm doing wrong? It's important to me that I loop through to create a table based on "p" and then edit that same "p" object. Just not sure how to do it. Pretty new to Rails.

Upvotes: 0

Views: 157

Answers (1)

Abram
Abram

Reputation: 41844

I think your problem is this line:

<%= i.hidden_field :true_weight, value: (i.actual_lbs + i.actual_oz/16)

You need to put p.actual_lbs and p.actual_oz

EDIT: By the way, you probably need to move the true weight calculation to your controller action (CREATE action). I don't think :true_weight will get passed as you intended it to, using the above method.

Upvotes: 1

Related Questions