relationships do
belongs_to :sender, MyApp.Accounts.User,
source_attribute: :sender_id,
destination_attribute: :id,
allow_nil?: false,
attribute_writable?: true
belongs_to :recipient, MyApp.Accounts.User,
source_attribute: :recipient_id,
destination_attribute: :id,
allow_nil?: false,
attribute_writable?: true
has_many :messages, MyApp.Conversations.Message
end
calculations do
calculate :other_user,
:struct,
expr(
if sender_id == ^arg(:current_user_id) do
recipient
else
sender
end
),
constraints: [instance_of: MyApp.Accounts.User] do
argument :current_user_id, :uuid, allow_nil?: false
end
end
I would like the calculation other_user to return an instance of the MyApp.Accounts.User resource. However, I get the error that: error: undefined function calculate/5 (there is no such import).
So, you won’t be able to this using an expression calculation, you’ll need to use an Elixir calculation. This is because expression calculations done in the data layer can’t return related resources, only relationships and runtime calculations can do that.
defmodule RecipientOrSender do
use Ash.Calculation
def load(_, _, _), do: [:recipient, :sender]
def calculate(records, _, context) do
Enum.map(records, fn record ->
if record.recipient.id == context.current_user_id do
record.recipient
else
record.sender
end
end)
end
end
Then you can do:
calculate :other_user,
:struct,
expr(
if sender_id == ^arg(:current_user_id) do
recipient
else
sender
end
) do
constraints [instance_of: MyApp.Accounts.User]
argument :current_user_id, :uuid, allow_nil?: false
end
Although, come to think of it, you could use a manual relationship, assuming you’re okay with using the actor in the standard way as opposed to passing in a current_user_id.
defmodule OtherUser do
use Ash.Resource.ManualRelationship
def load(records, _, %{api: api, actor: %{id: actor_id}}) do
records
|> Api.load!([:sender, :recipient])
|> Map.new(fn record ->
{record.id, [record.sender, record.recipient] |> Enum.filter(&(&1.id == actor_id))}
end)
end
def load(_, _, _), do: []
end
Haven’t actually run the above code snippets, they are just examples to get you going.