Quantcast
Channel: Pragmatic Forums | Posts in topic 'Multidimensional Array in rails with HTML'
Viewing all articles
Browse latest Browse all 4

Multidimensional Array in rails with HTML posted by Sam Ruby @ Sat, 16 Aug 2008 13:38:00 +0000

$
0
0

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 %>
    <tr>
    <td><input type="text" 
               name="products_to_buy[<%= item.product_id %>]" 
               value="<%= item.quantity %>"></td>
    <td><%= item.product.title %></td>
    </tr>
  <% 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 %>
    <tr>
    <td><%= hidden_field("item[]", 'product_id') %></td>
    <td><%= text_field("item[]", 'quantity') %></td>
    <td><%= @item.product.title %></td>
    </tr>
  <% end %>

Which would be used in the controller thus:

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

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


Viewing all articles
Browse latest Browse all 4

Trending Articles