Get user's role in given organization
Users belong to multiple organizations. In some orgs they are regular users and in others they are admins.
I need to add something to the User resource that takes an organization ID and returns the user's role in that organization. What would that thing be? A read action? A calculation?
There's an existing calculation called
organization_hierarchy
that let's me get a list of organizations the user is a member of, e.g.
21 Replies
It depends, what is a role?
A string?
A record?
If its a string, you'd use a calculation
it's an atom
Then yeah the calculation route would make sense 👍
organization_hierarchy
returns a list of organization structs, which have the role on them
So how would this calculation work? Would I not need to first load
the organizations?Its an expression calculation, using an aggregate
But it sounds like there may be a detail that matters here, you're saying there is no direct relationship between the given role and user and org?
i.e it might be somewhere in the hierarchy of roles?
Here's how I would write it in pure Elixir:
Or:
Oh, okay, so you don't actually need the hierarchy?
There is a role somewhere with
user_id
and organization_id
on it?Well, the hierarchy is just poorly named, it returns a list of organizations the user is a member of, and by default it returns them in tree format, but it can also be a flat list
which is the
format
option
This is confusing to me
organization
has a role
field?here's my idea: user has many user_orgs, user has many orgs through user_orgs. and user orgs resource has a role attribute. then you could load user orgs, take org id as argument and calculate the role.
You're right to be confused because I made a mistake in my explanation 🙂
Does user have a relationship to roles?
And organization has a relationship to roles?
i.e something liek this?
role | user_id, organization_id, name
?So the relationship is actually like this:
It is the
OrganizationMember
that has the role
(along with the user ID and org ID)Perfect
So my original answer should work
I made a mistake there though, sorry. i left out the field
:name
should be :role
?If that is what the attribute is called then yes
role_in_organization
equals "the role of the user's first organization_member where organization_id matches"OK. I think it's going to be a bit more complex but this gets me started
Thank you!
As a side note, you can do it w/ regular elixir like this
If you don't want to figure out the expression version
https://hexdocs.pm/ash/calculations.html#module-calculations
I have a very similar setup with User, Organization, and OrganizationMember. I tried this calculation (mostly to learn) and am getting the following error.
On
User
thank you.