armoucar
armoucar

Reputation: 408

Optional Nested has_one in ActiveAdmin

I have an one-to-one relationship between Order and ShippingAddress. Not always an Order has a ShippingAddress. Code for AA:

  f.inputs "Shipping address", for: [:shipping_address, f.object.shipping_address || ShippingAddress.new] do |shipping|
    shipping.input :firstname
    shipping.input :lastname
    shipping.input :address1
    shipping.input :address2
    shipping.input :phone
    shipping.input :country
    shipping.input :state
    shipping.input :city
    shipping.input :zip
  end

My problem is when editing an Order. It always tries to create a new shipping address and validate its fields - that are empty so it fails during validation. I don't want to create a Shipping Address when editing an order unless the fields were filled.

Upvotes: 0

Views: 395

Answers (2)

Matt Gibson
Matt Gibson

Reputation: 14949

This is what you need:

  accepts_nested_attributes_for :shipping_address, reject_if: proc { |attrs| attrs[:firstname].blank? }

Upvotes: 1

Andrey Deineko
Andrey Deineko

Reputation: 52347

Your issue is not with AA but with Rails.

What you want to use is reject_if:

has_one :shipping_address,
  reject_if: -> { |attrs| attrs[:firstname].blank? } # check any attributes you want

This way you ensure Rails won't try to create the association what it is not needed.

Upvotes: 1

Related Questions