Destroy on blank nested attribute

前端 未结 5 1069
醉酒成梦
醉酒成梦 2020-12-13 09:36

I would like to destroy a nested model if its attributes are blanked out in the form for the parent model - however, it appears that the ActiveRecord::Callbacks

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 09:51

    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?)
    

提交回复
热议问题