ruby-on-railsruby-on-rails-4accepts-nested-attributes

Rails 4 how to check if nested attributes _destroy flag is set from within model


I have model (container) that accepts nested attributes (including allow_destroy) for a has_one relationship to another model (reuse_request). There is a before_validation callback in the container model that I don't want to run if the the reuse_request is about to be destroyed in the same update.

Is there a way to check if the _destroy attribute has been passed from within the container model before_validation callback?

#container.rb
before_validation :set_code
has_one :reuse_request_as_previous, class_name: 'ReuseRequest', foreign_key: 'previous_container_id', dependent: :destroy, inverse_of: :previous_container
accepts_nested_attributes_for :reuse_request_as_new, :allow_destroy => true

def set_code
  if reuse_request_as_new && reuse_request_as_new.previous_container
    self.code = reuse_request_as_new.previous_container.code
  end
end

Solution

  • How about using .marked_for_destruction??

    def set_code
      return if reuse_request_as_new.marked_for_destruction?
      ...
    end