prajeesh
prajeesh

Reputation: 2392

Remove existing nested attribute record from database if the nested attribute is blank

i have the following code

order_controller.rb

def update
  order.update(order_params)
  redirect_to client_frequent_orders_path
end

def order_params
  params.require(:order).permit(
    :name,
    order_certifications_attributes: %i[id certification_id name]
  )
end

Model is as follows

order.rb

has_many :order_certifications, dependent: :destroy
has_many :certifications, through: :order_certifications
accepts_nested_attributes_for :order_certifications, allow_destroy: true

For each order we can select a certification from the certification drop down.

Consider that i selected a certification with name cert1 (id=50). It gets populated in the db.

Now i come back to the order and changed the selection from cert1 to " Select Certification". That is i removed the selection from the drop down.

Now the order_certification_attributes are not sent in the params.

So the previous certification "cert1" still exists in the database and shows up in the page.

How can i remove the existing order_certification record if the order_certification_attributes sent in the params is blank?

Upvotes: 0

Views: 34

Answers (1)

tenzin dorjee
tenzin dorjee

Reputation: 326

It could have been clearer if you have shown your model (relations), One solution could be passing _destroy true in form, another could be like this

def update
Order.transaction do
   order.order_certifications.destroy_all if order_params.dig(:order_certification_attributes).blank?
  order.update(order_params)
  redirect_to client_frequent_orders_path
  end
end

Upvotes: 1

Related Questions