Ash.Resource.Change.CascadeDestroy (ash v3.5.39)

View Source

Cascade a resource's destroy action to a related resource's destroy action.

Timing Control

The after_action? option controls when the cascade destroy occurs:

  • after_action?: true (default) - Runs as an after-action hook, making it safe for atomic actions
  • after_action?: false - Runs as a before-action hook

When after_action?: true, the change adds an after-action hook that explicitly calls destroy on any records related via the named relationship. It will optimise for bulk destroys where possible. This makes it safe to use in atomic actions, but might not be possible depending on the data layer setup (see warning below).

When after_action?: false, the change simply runs as a before_action. Requires keyset pagination on the primary read action of the targeted relation.

Beware database constraints

Think carefully before using this change with data layers which enforce referential integrity (ie PostgreSQL and SQLite) and you may need to defer constraints for the relationship in question.

See also:

  1. postgres.references.reference.deferrable DSL
  2. sqlite.references.reference.deferrable DSL
  3. PostgreSQL's SET CONSTRAINTS documentation
  4. SQLite's PRAGMA defer_foreign_keys documentation

Cascading notifications

By default notifications are disabled for the related destroy. This is to avoid potentially sending a lot of notifications for high-cardinality relationships.

Options

  • :relationship (atom/0) - Required. The name of the relationship to work on

  • :action (atom/0) - The name of the destroy action to call on the related resource. Uses the primary destroy by default.

  • :read_action (atom/0) - The name of the read action to call on the related resource to find results to be destroyed

  • :return_notifications? (boolean/0) - Return notifications for all destroyed records? The default value is false.

  • :after_action? (boolean/0) - If true, cascade destroys are done in after_action hooks. If false, they run as before_action hooks. Defaults to true for atomic action compatibility The default value is true.

Example

change {Ash.Resource.Change.CascadeDestroy, relationship: :comments, action: :destroy}

or, equivalently using Ash.Resource.Change.Builtins.cascade_destroy/2:

change cascade_destroy(:comments, action: :destroy)