Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/ash/actions/update/update.ex
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,22 @@ defmodule Ash.Actions.Update do
{:error, error}

{changeset, manage_instructions} ->
# Recompute changed? after setup_managed_belongs_to_relationships
# may have set FK attributes via force_change_attribute (e.g. when
# manage_relationship is called from before_transaction hooks on
# update actions). Without this, the changed? flag computed before
# the func callback would be false, causing the DB update to be
# skipped entirely.
changed? =
Ash.Changeset.changing_attributes?(changeset) or
not Enum.empty?(changeset.atomics)

changeset =
changeset
|> Ash.Changeset.put_context(
:changed?,
changeset.context[:changed?] || changed?
)
|> Ash.Changeset.require_values(
:update,
true
Expand Down
37 changes: 37 additions & 0 deletions test/manage_relationship_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,22 @@ defmodule Ash.Test.ManageRelationshipTest do

change manage_relationship(:parent_resource, on_match: :update)
end

update :update_create_parent_in_hook do
require_atomic? false

change fn changeset, _context ->
Ash.Changeset.before_transaction(changeset, fn changeset ->
Ash.Changeset.manage_relationship(
changeset,
:parent_resource,
%{name: "created-in-hook"},
type: :create,
on_no_match: :create
)
end)
end
end
end

attributes do
Expand Down Expand Up @@ -1289,4 +1305,25 @@ defmodule Ash.Test.ManageRelationshipTest do
assert names == ["new1", "existing1", "new2", "existing2"]
end
end

describe "manage_relationship called from before_transaction hook on update" do
test "creates related record via belongs_to when manage_relationship is called in before_transaction" do
related =
RelatedResource
|> Ash.Changeset.for_create(:create, %{required_attribute: "test"})
|> Ash.create!()

assert related.parent_resource_id == nil

updated =
related
|> Ash.Changeset.for_update(:update_create_parent_in_hook, %{})
|> Ash.update!()

assert updated.parent_resource_id != nil

{:ok, loaded} = Ash.load(updated, :parent_resource)
assert loaded.parent_resource.name == "created-in-hook"
end
end
end
Loading