Calculate the sum of a has_many relationship field

I have a User resource which has_many Credits. The Credit resource has a points attribute. How can I create a points calculate attribute in User which stores the sum of all points?

defmodule Animina.Accounts.User do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer

  attributes do
    uuid_primary_key :id
    attribute :username, :ci_string, allow_nil?: false
  end

  relationships do
    has_many :credits, Animina.Accounts.Credit
  end
  # ...
defmodule Animina.Accounts.Credit do
  use Ash.Resource,
    data_layer: AshPostgres.DataLayer
    
  attributes do
    uuid_primary_key :id

    attribute :points, :integer do
      constraints min: 1,
                  allow_empty?: false
    end
  end

  relationships do
    belongs_to :user, Animina.Accounts.User do
      attribute_writable? true
    end
  end
  # ...

I think this should work.

aggregates do
  sum :credit_points, :credits, :points
end

https://hexdocs.pm/ash/dsl-ash-resource.html#aggregates-sum

1 Like