I will change the names of my models to illustrate my situation.

Here's the thing, I have a model called "Author" that has an association of "has_many :books, dependent: :destroy" with the Book model. In this Book model, which has an association of "belongs_to" with the first one, I need to perform a validation to determine whether the record in question from Book can be deleted or not.

Validation is a method that is executed in Book's "before_destroy" callback.

What I want to happen is the following: I want the books associated with it to also be deleted when executing the "destroy" of the Author. However, if a Book does not pass the before_destroy validation, I want that specific book to remain, but the execution of the cascade destroy of possible books associated with that author continues to be executed. Furthermore, the author cannot be deleted if at least one of his books fails to be deleted, to avoid having records with broken associations.

I've already tried to do this in a few ways:

1 - Add items to "errors"

before_destroy :validate, prepend: true

def validate
    validation = ...

    errors.add(:base, "Error message") if validation
end

2 - Return "false"

before_destroy :validate, prepend: true

def validate
    validation = ...

    if validation
        return false
    end
end

3 - Put both things together, add errors to "errors" and return false.

4 - Use "throw"

before_destroy :validate, prepend: true

def validate
    validation = ...

    if validation
        throw(:abort)
    end
end

In the first three attempts, the Author record was deleted and so were the books (even those that did not pass validation)

On the fourth attempt, the record was not deleted but it stopped the deletion of the next books, which is not what I want.

Any solution?

0

There are 0 answers