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!
i still can’t get the example on page 340 to work. ` order = Order.new params[:products_to_buy].each do |prd_id, qty| product = Product.find(prd_id) order.line_items « LineItem.new(:product => product, :quantity => qty) end order.save ` What HTML do i need to get the param products_to_buy to have 2 columns? thanks
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”:http://railscasts.com/episodes/73, “74”:http://railscasts.com/episodes/74, and “75”:http://railscasts.com/episodes/75
Now i get it ;) thanks for the info Sam!