small medium large xlarge

Img_20120421_100811_pragsmall
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!

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

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

Samr_small_pragsmall
16 Aug 2008, 15:49
Sam Ruby (634 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 %>
    <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

Img_20120421_100811_pragsmall
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