Search code examples
ruby-on-railsform-forfields-for

Rails: how do I layout forms different to datamodel flow?


I have a data model that represents a weekly order. Eg. my order might be

Monday: 2 x coffee
Tuesday: 2 x tea
Wednesday: 3 x coffee, 4x tea 

I pay for my order at the end of the week.

I represent this as:

Order
   has_many: days

Day
   has_many: line_items

and I have a form of the form:

form_for @order
   fields_for :days
       fields_for :line_items

which Produces a form like

Monday
   Tea x 2
   Coffee x 0
Tuesday
   Tea x 1
   Coffee x 3
Wednesday
   Tea x 1
   Coffee x 2

I want my form to be a table like this:

            Monday     Tuesday     Wednesday

Coffee       2           1           1 
Tea          0           3           2
Add+

I can do this by looping thorough Order.days.each do |day| day.each etc trying to figure out the name of the input field "order[]days[]line_items[]" and adding hidden variables for line_item and day but it's turning out to be harder than it first looks.

Am I missing a simpler way?


Solution

  • The way I did it was to build up the form elements in a hash and ad them to the form after

    form_for @order
      fields_for :days
          fields_for :line_items
              hash[line_item.product][day.theday] = select_tag...
    

    then iterate through days and products and put in the appropriate select tag in the table