fix: set tenant attribute in bulk create

fixes: #830
This commit is contained in:
Zach Daniel 2024-01-12 08:19:55 -05:00
parent db7e42713c
commit 59e50f8dfa
2 changed files with 50 additions and 1 deletions

View file

@ -269,6 +269,7 @@ defmodule Ash.Actions.Create.Bulk do
})
|> Ash.Actions.Helpers.add_context(opts)
|> Ash.Changeset.set_context(opts[:context] || %{})
|> set_tenant()
|> Ash.Changeset.prepare_changeset_for_action(action, opts)
end
@ -474,6 +475,19 @@ defmodule Ash.Actions.Create.Bulk do
|> set_lazy_matching_defaults(lazy_matching_default_values)
end
defp set_tenant(changeset) do
if changeset.tenant &&
Ash.Resource.Info.multitenancy_strategy(changeset.resource) == :attribute do
attribute = Ash.Resource.Info.multitenancy_attribute(changeset.resource)
{m, f, a} = Ash.Resource.Info.multitenancy_parse_attribute(changeset.resource)
attribute_value = apply(m, f, [changeset.tenant | a])
Ash.Changeset.force_change_attribute(changeset, attribute, attribute_value)
else
changeset
end
end
defp handle_params(changeset, false, action, _opts, input, _argument_names) do
Ash.Changeset.handle_params(changeset, action, input)
end

View file

@ -32,16 +32,37 @@ defmodule Ash.Test.Actions.BulkCreateTest do
end
end
defmodule Org do
@moduledoc false
use Ash.Resource,
data_layer: Ash.DataLayer.Ets
attributes do
uuid_primary_key :id
end
actions do
defaults [:create]
end
end
defmodule Post do
@moduledoc false
use Ash.Resource,
data_layer: Ash.DataLayer.Ets,
authorizers: [Ash.Policy.Authorizer]
alias Ash.Test.Actions.BulkCreateTest.Org
ets do
private? true
end
multitenancy do
strategy :attribute
attribute :org_id
end
actions do
defaults [:create, :read, :update, :destroy]
@ -104,6 +125,13 @@ defmodule Ash.Test.Actions.BulkCreateTest do
timestamps()
end
relationships do
belongs_to :org, Org do
allow_nil? false
attribute_writable? true
end
end
end
defmodule Registry do
@ -111,6 +139,7 @@ defmodule Ash.Test.Actions.BulkCreateTest do
use Ash.Registry
entries do
entry Org
entry Post
end
end
@ -125,11 +154,17 @@ defmodule Ash.Test.Actions.BulkCreateTest do
end
test "returns created records" do
org =
Org
|> Ash.Changeset.for_create(:create, %{})
|> Api.create!()
assert %Ash.BulkResult{records: [%{title: "title1"}, %{title: "title2"}]} =
Api.bulk_create!([%{title: "title1"}, %{title: "title2"}], Post, :create,
return_records?: true,
return_errors?: true,
sorted?: true
sorted?: true,
tenant: org.id
)
end