Create an Ash Resource from a form before submitting

New to Ash so let me know if there is a better way to accomplish what I’m attempting.

I have an AshPhoenix.Form created with AshPhoenix.Form.for_create. Naturally, when I submit this form it creates a new resource in my Postgres database and returns {:ok, %MyNewResource{}}.

Is there a way I can get %MyNewResource{} before I submit the form? The reason I want it is because that Ash.Resource has calculations on it that I rely on in order to make an external API call when the form is submitted.

So my desired flow is:

  1. User hits submit
  2. I make a call to the Google Calendar API, passing in the result of a calculated field
  3. I merge the resulting google_calendar_event_id into params
  4. I call AshPhoenix.Form.submit with the merged params

I can’t figure out a good way to get the result of a calculated field in step 2 without having my resource, and manually creating the resource from the form params sounds like the wrong way to do it.

My suggestion would be to put this in the action itself, and then to use Ash.Changeset.apply_attributes to get the result, and Api.calculate to calculate the individual value.

create :your_action do
  change fn changeset, _ -> 
    Ash.Changeset.before_transaction(changeset, fn changeset -> 
      {:ok, temporary_result} = Ash.Changeset.apply_attributes(changeset)
       value = YourApi.calculate(temporary_result, :calculation)
       Ash.Changeset.change_attribute(changeset, :attr, value)

If the calculation is only used on creation to formulate an attribute, the calculation itself may not be necessary, and your logic can just go in the change (which can live in its own module of course, i.e change LookupInSomeApi

1 Like