Form_for with cart with list of cart items

How can one make use of form_for, and ideally fields_for, to produce a
clean form that
allows editing a collection within a base object?

Specific example, say you have a cart which has a list of cart items.
Then you’d like to be able to do something like (logically):

<% form_for :cart do |form| %>
<% fields_for :cart_items[] do |cart_item| %>
<%= cart_item.text_field :quantity %>

<% end %>
<% end %>

However, obviously you can’t pass “:cart_items[]” as a symbol.

See pp. 476 and 483 in the recent AWDwR 2nd Ed. beta book for most
relevant references. Blending these two pages together, these would
have you believe that perhaps something like this:

<% form_for :cart do |form| %>
<% for @cart_item in cart.cart_items %>
<%= form.text_field “cart_item[]”, :quantity %>

<% end %>
<% end %>

might work, but it doesn’t, as we choke in ActionView FormHelper with:

undefined method `merge’ for :quantity:Symbol

which I’ve not investigated further since this just feels wonky and
like I’m doing something wrong.

I’m currently of the opinion that the only approach that works is to
pitch form_for and fields_for (a bummer), use start_form_tag, and build
everything up with the base tags. So:

<%= start_form_tag %>
<% for @cart_item in cart.cart_items %>
<%= text_field “cart_item[]”, ‘quantity’ %>

<% end %>
<%= end_form_tag %>

Nothing else seems to allow using ‘[]’ to connote that the object’s id
should be used to allow for production of an appropriate hash keyed on
the cart item id to allow for easy ActiveRecord updating via
update_params() on an object id in the controller. E.g.:

CartItem.update(params[:cart_item].keys, params[:cart_item].values)

which, as an end goal, is lovely.

Does anyone know of an approach that works that doesn’t use the
start_form_tag example?

I use something like

<% form_for :cart, @cart, :url => { :action => “save” } do |f| %>
<%= f.text_field :attr1 %>
<% 0.upto(@cart.rows.size) do |i| %>
<% fields_for “rows[#{i}]”, @cart.rows[i] do |row| %>
<%= row.text_field :price %>
<% end %>
<% end %>
<% end %>

Regards
Simo
addsw.it

shaper wrote:

How can one make use of form_for, and ideally fields_for, to produce a
clean form that
allows editing a collection within a base object?

Specific example, say you have a cart which has a list of cart items.
Then you’d like to be able to do something like (logically):

<% form_for :cart do |form| %>
<% fields_for :cart_items[] do |cart_item| %>
<%= cart_item.text_field :quantity %>

<% end %>
<% end %>