How can I add multiple singleton elements to one form using Rails?

I have three models, which need to work together - product

, line_product

and order

where line_product

the mirror product

for order

. To make it look like this:

product.rb

has_many :line_products

      

order.rb

has_many :line_products

      

line_product.rb

belongs_to :order
belongs_to :product

      

And I would like to make a form where there is a list of products with an input field next to each, and the user can enter any quantity (quantity) for any product, press submit and all products with an invoice greater than 0 in their form will become line_products

for order

where order.id: 1

(for example). At the moment, only the last item is added to the order.

How can i do this?

Edit

The form looks like this:

= 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'

      

+3


source to share


2 answers


You hit the expected behavior. Actually how the rails form the checkbox handles that are unchecked. Actually it is more of an HTTP post issue generating HTML with rails / haml, this is not a problem.



Use array form POST array from HTML form without javascript

0


source


There are several ways to deal with this, for example you can go down the path of use accepts_nested_attributes

, which is a fairly general way of creating forms that create / edit multiple objects and then process that data.

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

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

      

This will result in what params[:count]

will be a hash of the form



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

      

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

Then you need some controller code to iterate over this hash and create the appropriate line_product objects

0


source







All Articles