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:Jump to solution
That's right, this makes it
```elixir
change after_action(fn changeset, user, context ->
profile = Ash.load!(user, :profile) |> Map.fetch!(:profile)...
6 Replies
you probably want :create, not :direct_control
for create it's
I tried that as well, but it creates new profiles 🤔
This is my action
what exacly are you passing for a profile? Ash compares primary keys to see if the old/new values are the same by default.
I'm guessing Ash can't find a relation purely on that data. So what are my options considering the user may be registering for the first time, or signing in for an x time
In that case I would probably just add an after_action that does the lookup/write or use an upsert on the fk on profile.
Solution
That's right, this makes it