Ash FrameworkAF
Ash Framework8mo ago
29 replies
Chaz Watkins

Error when using before_action hook to set required relationship attribute

I'm using a before action to lookup and set the :state_id by the state's name or code.

However, the change doesn't seem to be running as I never see the Logger.debugs and I get changeset errors that :state_id is required.

Have I misconfigured this hook?

Action

create :create do
  primary? true
  upsert? true
  upsert_identity :unique_google_place
  upsert_fields {:replace_all_except, [:id, :state_id, :inserted_at]}
  skip_unknown_inputs :*

  change __MODULE__.Changes.SetState,
    where: [present(:google_state), absent(:state_id)]
end


Change Module

defmodule Boring.Google.Place.Changes.SetState do
  @moduledoc false
  use Ash.Resource.Change

  require Logger

  @impl Ash.Resource.Change
  def change(changeset, _opts, context) do
    Ash.Changeset.before_action(changeset, fn changeset ->
      state = Ash.Changeset.get_argument_or_attribute(changeset, :google_state)
      Logger.debug("Setting state for #{state}")

      opts = Ash.Context.to_opts(context)

      case Boring.Locations.get_state_by_name_or_code(state, opts) do
        %Boring.Locations.State{} = matching_state ->
          Ash.Changeset.force_change_attribute(changeset, :state_id, matching_state.id)

        _ ->
          changeset
      end
    end)
  end
end
Solution
GitHub
Versions erlang 27.3.4.1 elixir 1.18.4 ash 3.5.12 ash_postgres 2.5.22 ecto 3.12.5 ecto_sql 3.12.1 Originally found and reported in Discord Support on 6/16/2025 and tried upgrading the latest versio...
Error when using before_action hook to set required relationship at...
Was this page helpful?