Home > Software design >  Rails double nested form with active admin
Rails double nested form with active admin

Time:11-22

I have associations as follows:

variant has_may colours and colours has_many sizes. I am using active admin gem for managing backend activities. My models looks like,

class Variant < ApplicationRecord

  has_many :variant_colours, dependent: :destroy

  accepts_nested_attributes_for : variant_colours, allow_destroy: true
end

class VariantColor < ApplicationRecord
  belongs_to :variant

  has_many :variant_sizes, dependent: :destroy

  accepts_nested_attributes_for :variant_sizes, allow_destroy: true
end

class VariantSize < ApplicationRecord
  belongs_to :variant_color
end

It is building variant_colours form with given fields but it is not building variant_sizes form under variant colours. Building meaning it does not populate fields on the form(UI)

form do |f|
    f.inputs do
      f.input :name
      f.input :product
      f.input :sku
      f.input :stock_quantity
      f.inputs do
        f.has_many :variant_colors, heading: 'Variant Colors',
                                allow_destroy: true,
                                new_record: true do |color_form|
          color_form.input :color
          color_form.input :sku_code
          color_form.input :stock
          color_form.inputs do
            color_form.has_many :variant_sizes, heading: 'Variant Sizes',
                                    allow_destroy: true,
                                    new_record: true do |size_form|
              size_form.input :size
              size_form.input :sku_code
              size_form.input :stock
            end
          end
        end
      end
    end
    f.actions
  end

CodePudding user response:

May not need to wrap f.has_many with anything, so you could try removing one or both of the nested f.inputs and color_form.inputs that you have wrapping your has_many input blocks in the form.

My next thought would be, how are you declaring the permitted params in your controller? They probably need to be something along the lines of:

permit_params :name, :product, :sku, :stock_quantity, 
  variant_colors_attributes: [
    :color, :sku_code, :stock, :_destroy, 
    # I don't think I've ever tried to double nest in this way, you may need diff syntax
    variant_sizes_attributes: [:size, :sku_code, :stock, :_destroy]
  ]

My guess is the issue is in your permitted params.

  • Related