before_action in bulk_create

I'm implementing some logic that would bulk_destroy existing records and bulk_create in a transaction
create :replace_signatures do
accept :*

change relate_actor(:user)

change fn changeset, context ->
changeset
|> Ash.Changeset.before_action(fn changeset ->
Emails.EmailSignature.list_signatures!(
actor: context.actor,
tenant: context.tenant
)
|> Ash.bulk_destroy!(:destroy, %{}, tenant: context.tenant)

changeset
end)
end
end
end
create :replace_signatures do
accept :*

change relate_actor(:user)

change fn changeset, context ->
changeset
|> Ash.Changeset.before_action(fn changeset ->
Emails.EmailSignature.list_signatures!(
actor: context.actor,
tenant: context.tenant
)
|> Ash.bulk_destroy!(:destroy, %{}, tenant: context.tenant)

changeset
end)
end
end
end
and then
Ash.bulk_create(new_signatures, EmailSignature, :replace_signatures,
actor: %{id: user.id},
tenant: org.id,
return_records?: true,
assume_casted?: true
)
Ash.bulk_create(new_signatures, EmailSignature, :replace_signatures,
actor: %{id: user.id},
tenant: org.id,
return_records?: true,
assume_casted?: true
)
but the before_action gets called before every batch, what's the idiomatic way to achieve this behavior and having the before_action running only once in transaction? Thanks
4 Replies
ZachDaniel
ZachDaniel4mo ago
When you say before every batch do you mean for each record? You can define a change module and implement the batch callbacks to run code before the entire batch IIRC this is covered in the multi step actions guide
Elixord
Elixord4mo ago
Hexdocs Search Results
Searched ash-3.5.15 for multi-step-actions
ash-3.5.15 | extras
Marco Dell'Olio
Marco Dell'OlioOP4mo ago
would that previous change in transaction?
ZachDaniel
ZachDaniel4mo ago
Yes, before_batch is in the same transaction as the batch

Did you find this page helpful?