small medium large xlarge

19 May 2008, 13:36
Emilio Blanco (4 posts)

Hi! In page 335 of the book, there shows an example of has_many declaration, where it process the order, and it uses the params array and slipts it in two variables “prd_id” and “qty”, whats the HTML to get this behavior, can i have more than 2 columns in the array? Thanks in advance!

16 Aug 2008, 00:24
Emilio Blanco (4 posts)

i still can’t get the example on page 340 to work. ` order = params[:products_to_buy].each do |prd_id, qty| product = Product.find(prd_id) order.line_items « => product, :quantity => qty) end ` What HTML do i need to get the param products_to_buy to have 2 columns? thanks

16 Aug 2008, 15:49
Sam Ruby (633 posts)

It is not exactly an array, it actually is a hash. Here’s some HTML which will product a products_to_buy hash containing product ids and their corresponding quantity:

  <% for item in @order.line_items %>
    <td><input type="text"
               name="products_to_buy[<%= item.product_id %>]"
               value="<%= item.quantity %>"></td>
    <td><%= item.product.title %></td>
  <% end %>

More common, however, is not to have a single value for every key, but a hash (this is mentioned briefly on page 650).

  <% for @item in @order.line_items %>
    <td><%= hidden_field("item[]", 'product_id') %></td>
    <td><%= text_field("item[]", 'quantity') %></td>
    <td><%= @item.product.title %></td>
  <% end %>

Which would be used in the controller thus:

order = params[:item].values.each do |item|
  product = Product.find(prd_id)
  order.line_items << => item['product_id'], :quantity => item['quantity'])

Still more common is to use form_for (described on pages 508-510). More information on this can be found in Railscasts “73”:, “74”:, and “75”:

16 Aug 2008, 22:53
Emilio Blanco (4 posts)

Now i get it ;) thanks for the info Sam!

You must be logged in to comment