Destroy on blank nested attribute

I would keep the :reject_if block but insert :_destroy => 1 into the attributes hash if your conditions are met. (This is useful in the cases where it’s not convenient to add _destroy to the form code.)

You have to do an extra check to see if the record exists in order to return the right value but the following seems to work in all cases for me.

accepts_nested_attributes_for :tour_dates, :reject_if => :reject_tour, :allow_destroy => true

def reject_tour(attributes)
  exists = attributes['id'].present?
  empty = attributes.slice(:when, :where).values.all?(&:blank?)
  attributes.merge!({:_destroy => 1}) if exists and empty # destroy empty tour
  return (!exists and empty) # reject empty attributes
end

You could apply when all attributes are blank by just changing the empty calculation to:

empty = attributes.except(:id).values.all?(&:blank?)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)