Forum: Ruby on Rails binding an array to multiple text fields in a form

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
B199c6556fec872d272086be15c5e4ab?d=identicon&s=25 Robert La ferla (rlaferla)
on 2007-07-05 02:12
(Received via mailing list)
I have a model that has the following classes: ShoppingList, Item and
Product.

-- *Product* is just a list of product names:  Apple, Orange, Banana,
Pear,
Grape.  The table has two columns: ID and NAME.

-- A *ShoppingList* has a name (string) and many *Item* objects.

-- Each *Item* has a *quantity* (integer) and to-one relationship to
a
*Product*.

My ShoppingList's edit view has a form that contains a textfield for
the name of
a shopping list and a table of items and their quantities:

Name:  MyShoppingList

Qty.  Item
3      Apples
0      Oranges
1      Pear

The Qty. is an editable text field.  The Item is a non-editable text
label.

The model object for this view is, of course, a ShoppingList.

I am trying to bind each text field to the quantity attribute of each
item in the shopping list.  I tried something like this but it doesn't
work because Rails wants an instance variable to bind to.  How do I
properly bind my array?

<% @shopping_list.items.each do |item| %>
<tr>
<td><%= text_field("shopping_list.items[" + item.id.to_s +
"].quantity",
item.quantity, :size => 3) %></td><td><%= (Product.find
item.product_name_id).name%></td>
</tr>
<% end %>
B199c6556fec872d272086be15c5e4ab?d=identicon&s=25 Robert La ferla (rlaferla)
on 2007-07-05 03:20
(Received via mailing list)
Let me try to simplify this problem:

To create the html table, I have this code:

<% @shopping_list.items.each do |item| %>
<tr>
<td><%= text_field("item.quantity", item.quantity, :size => 3) %></
td><td><%= (Product.find item.product_name_id).name%></td>
</tr>
<% end %>

But it generates this error:

`@item.quantity' is not allowed as an instance variable name

This tells me that you can only bind instance variables and not
relationships off them.  Is this true?  Where can I find a detailed
explanation on how binding forms to variables work?
B199c6556fec872d272086be15c5e4ab?d=identicon&s=25 Robert La ferla (rlaferla)
on 2007-07-05 15:37
(Received via mailing list)
Never mind.  I figured it out.  The solution is to use the fields_for
tag.  The problem was editing multiple models in one large form.
This topic is locked and can not be replied to.