How to trigger creation of other resources upon creation of one?

I’m trying to setup multitenancy for ash framework, such that one user could be a part of more than one organizations.
So there is an m2m relationship between User and Organization through Team.

However, as an initial thing, I want to setup a ‘personal’ organization for every user for them to fiddle around with, without going through the hassle of creating an org / team.

How do I trigger creation of this org by default when a user signs up?

You can add a change with an after action hook to your user resource:

changes do
  change after_action(fn changeset, result, _context -> 
     # create personal organization here
  end), on: [:create] # only do this when a user is created.
end
1 Like

Right now this feels magical to me.

Could you please point me in the direction of the documentation / code which would have helped me reach this solution on my own?

The documentation for Actions can be found here, additionally you can look at the documentation for the Ash.Changeset module here, which describes the Changeset lifecycle and hooks. (NOTE: These links points to Ash 3.0 rc)

Thanks for posting those links! In this particular example I used a “builtin change” as well, after_action/1. To see all built in changes here: Ash.Resource.Change.Builtins — ash v3.0.0-rc.29

2 Likes