3

I have three models that need to work together - product, line_product and order, where line_product mirrors product for order. So that it looks like so:

product.rb

has_many :line_products

order.rb

has_many :line_products

line_product.rb

belongs_to :order
belongs_to :product

And I'd like to make a form where there's a list of products with an input field next to each and a user can input any number (count) for any product, click submit and all the products with a count more than 0 in their form, will become line_products for order where order.id: 1 (for example). As of now only the last product gets added to the order.

How could I do this?

Edit

The form looks like so:

= form_for @line_product do |lp|
  = lp.hidden_field :order_id, value: Order.last.id
  %section#product_list
    - if notice
      %section.notice=notice
    %ul#products
      -@products.each do |p|
        %li.product_list
          %article.product
            %section.product_left
              = image_tag p.image.url(:medium)
              %div.clear
              %span.price= number_to_currency(p.price,:unit=>'€ ')

            %section.product_right
              %section.product_about
                %span.title= p.title
                %span.description= p.description
                %span.description.desceng= p.description_eng
                = lp.hidden_field :product_id, value: p.id

              %section.product_order
                = lp.number_field(:count, min: '0', value: '', class: 'product_count')


  %section#order_accepting
    = lp.submit "Add to cart", class:'add_to_cart'
Xeen
  • 6,955
  • 16
  • 60
  • 111

2 Answers2

0

You're hitting expected behavior. This is actually how rails forms handle checkboxes that are unchecked. This actually more of an HTTP form post question, generating the HTML with rails / haml isn't the issue.

Use an array form POST an array from an HTML form without javascript

Community
  • 1
  • 1
EnabrenTane
  • 7,428
  • 2
  • 26
  • 44
0

There are quite a few ways you could handle this, for example you could go down the route of using accepts_nested_attributes which is a fairly generic way of generating forms that create/edit multiple objects and then handling that data.

A slightly simpler alternative for this particular case would be to generate a single number input for each product (rather than the pair of hidden input and number input you have)

number_field_tag "count[#{product.id}]"

This will result in params[:count] being a hash of the form

{ "1" => 23, "2" => "", "3"=> "1"}

Assuming that you had 3 products with ids 1,2,3 and that you had entered 23 for the first quantity and 1 for the last.

You would then need some controller code to iterate over this hash and build the corresponding line_product objects

Frederick Cheung
  • 83,189
  • 8
  • 152
  • 174