Question

I am trying to create a small accounting system. Here I have some products. Each month I want to write down how many of each product each user bought.

Lets say I have 3 users and 4 products. I want a 3 by 4 table with all the users names on the left and the products on the top. In each field I want to be able to write how many of that particularly item that user bought.

I have tried the following, however the fields are not unique, so only the last one gets submitted. How should I proceed?

= simple_form_for(:lines, url: lines_url) do |f|
  - @users.each do |user|
    tr
      td= user.name
      - @products.each do |product|
        td
          = f.fields_for user do |u|
            = u.fields_for product do |p|
              = p.fields_for Line.new do |l|
                = l.text_field :quantity

EDIT:

I found that this will also work, howver, it is rather hackish:

= simple_form_for(:lines, url: lines_url) do |f|
  - @users.each do |user|
    tr
      td= user.name
      - @products.each do |product|
        td
          = text_field :lines, "#{user.id}][#{product.id}"

Notice the ][ in the text_field.

Was it helpful?

Solution

I have had this problem a few times and have come up with this:

= simple_form_for(:lines, url: lines_url) do |f|
  - @users.each_with_index do |user, index|
    %tr
      %td= user.name
      - @products.each do |product|
        %td
          = f.fields_for user do |u|
            = u.fields_for index do |u|
              = u.fields_for product do |p|
                = p.fields_for Line.new do |l|
                  = l.text_field :quantity

The fields_for index means that it comes out as lines[user][0][product][line] etc. , which is how Rails usually deals with submitting multiple objects. The params come in as:

{
  "0" => some_data,
  "1" => some_other_data
}

which is a bit weird but how it is meant to look. I seem to remember having problems with using this technique with as many levels of nesting as you have, but it should help give you some ideas.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top