Ash FrameworkAF
Ash Framework3y ago
21 replies
Mylan Connolly

Using manage_relationship with nested relationships

I have three resource modules:

defmodule Patient do
  use Ash.Resource, data_layer: AshPostgres.DataLayer

  postgres do
    table "patients"
    repo Repo
  end

  attributes do
    uuid_primary_key(:id)
    attribute(:first_name, :string)
    attribute(:last_name, :string)
    timestamps()
  end

  relationships do
    has_many :event_series, EventSeries
  end
end

defmodule EventSeries do
  use Ash.Resource, data_layer: AshPostgres.DataLayer

  postgres do
    table "event_series"
    repo Repo
    
    custom_indexes do
      index [:patient_id, :initial_date], unique: true
    end
  end

  attributes do
    uuid_primary_key(:id)
    attribute(:initial_date, :date)
    timestamps()
  end

  relationships do
    belongs_to :patient, Patient, allow_nil?: false
    has_many :exams, Exam
  end
end

defmodule Exam do
  use Ash.Resource, data_layer: AshPostgres.DataLayer

  postgres do
    table "exams"
    repo Repo
  end

  attributes do
    uuid_primary_key(:id)
    attribute(:performed_on, :date)
    timestamps()
  end

  relationships do
    belongs_to :event_series, EventSeries, allow_nil?: false
  end
end


With this in place, I was able to figure out how to insert patients into the
database pretty easily, however my problems arose when trying to do the exams.

The exams are loaded from an outside data source where we derive the event series
based on a date value. So what I tried to do was:

Exam
|> Ash.Changeset.for_create(:create, %{performed_on: performed_on})
|> Ash.Changeset.manage_relationship(:event_series, %{patient_id: patient_id, initial_date: examdate}, type: :append_and_remove, on_no_match: :create)
|> Api.create()


When doing this, an error is returned saying that the event series is invalid
because the patient relationship is not defined. Is it possible to do this with
a call to manage_relationship or am I fundamentally missing something?

Thanks so much for any assistance, Ash is very cool so far!
Was this page helpful?