Ash FrameworkAF
Ash Frameworkβ€’3y agoβ€’
41 replies
miguels

How to create has_one relationships in a nested form

I have a resource called Transaction that has a has_one relationship with a resource called RecurrencePattern. When creating a new transaction (usually through a form in LV) I want to also create a matching recurrence_pattern. This works great when using the
create
action directly, but I'm getting an error when using an
AshPhoenix.Form
(I believe I got it to work at some point but don't know how to get back there again πŸ˜… )

This works:
Transaction.create!(%{
  amount: 100,
  description: "Test transaction",
  date: Date.utc_today(),
  category_id: context.category.id,
  currency_id: context.currency.id,
  method_id: context.method.id,
  rate_id: context.rate.id,
  type_id: context.type.id,
  end_date: Timex.shift(Date.utc_today(), months: 1),
  recurrence_pattern: %{
    recurrence_type_id: context.recurrence_type.id,
    count: 5
  }
})


This gives me an error:
params = %{
  amount: 100,
  description: "Test transaction",
  date: Date.utc_today(),
  category_id: context.category.id,
  currency_id: context.currency.id,
  method_id: context.method.id,
  rate_id: context.rate.id,
  type_id: context.type.id,
  end_date: Timex.shift(Date.utc_today(), months: 1),
  recurrence_pattern: %{
    recurrence_type_id: context.recurrence_type.id,
    count: 5
  }
}

transaction =
  AshPhoenix.Form.for_create(Transaction, :create,
    api: Transactions,
    forms: [auto?: true]
  )
  |> AshPhoenix.Form.add_form(:recurrence_pattern)
  |> AshPhoenix.Form.validate(params)
  |> AshPhoenix.Form.submit!()


The error inside the changeset:
%Ash.Error.Changes.Required{
  field: :transaction_id,
  type: :attribute,
  resource: RecurrencePattern,
  changeset: nil,
  query: nil,
  error_context: [],
  vars: [],
  path: [],
  stacktrace: #Stacktrace<>,
  class: :invalid
}
Was this page helpful?