Ash FrameworkAF
Ash Framework6mo ago
9 replies
Joan Gavelán

Conditional Relationship Creation

I'm trying to create a profile when a user registers, but only if one doesn't already exist.

I tried using manage_relationship/4 with type: :direct_control and it does create the profile, but if the user already has one - with more data fulfilled - it overwrites it with the partial available data at user registration — which is not ideal.

Is manage_relationship/4 the right way to handle this? Or should I use an after_action hook to conditionally create the profile?
Solution
That's right, this makes it

change after_action(fn changeset, user, context ->
   profile = Ash.load!(user, :profile) |> Map.fetch!(:profile)

   if is_nil(profile) do
     MyApp.Users.create_profile!(
       changeset.arguments.profile,
       actor: user,
       authorize?: false
     )
   end

   {:ok, user}
 end)
Was this page helpful?