Access struct attributes for change action built-in set_attribute

In an embedded resource, I want to a create action that accepts a struct as an argument and use several but not all of the attributes for constructing my embedded resource.

There doesn’t seem to be an arg/2 to access a property of a struct or map, and using Map.get/2 and dot notation also don’t seem to work.

Is this something that is supported via create set_attribute()? Or will I need to do something not necessarily out of the box?

You will need something custom. set_attribute/2 is a builtin change but you can add your own changes too:

change fn changeset, _ -> 
  case Ash.Changeset.fetch_argument(changeset, :something) do
    {:ok, value} ->   Ash.Changeset.change_attribute(changeset, :something_else, some_value)
    :error -> changeset
  end
end

Or you can put it in your own module:

defmodule CustomChange do
  use Ash.Resource.Change

  def change(changeset, _, _) do
    case Ash.Changeset.fetch_argument(changeset, :something) do
      {:ok, value} ->   Ash.Changeset.change_attribute(changeset, :something_else, some_value)
      :error -> changeset
    end
  end
end
create :thing do
  change CustomChange
end

Thanks, I had a feeling that would be the case but just wanted to double check just in case.

1 Like