How to validate that a belongs_to exists?

I have a Product which belongs_to a Category. How can I validate that the field category_id is not nil and how can I validate that there is a Category with that id?

defmodule App.Shop.Product do
  use Ash.Resource, data_layer: Ash.DataLayer.Ets

  attributes do
    uuid_primary_key :id
    attribute :name, :string
    attribute :price, :decimal
  end

  relationships do
    belongs_to :category, App.Shop.Category do 
      attribute_writable? true 
    end
  end

  actions do
    defaults [:create, :read, :update, :destroy]
  end
end
2 Likes

In ash_postgres this happens automatically. In Ash.DataLayer.Ets we don’t have foreign key constraints (because ets doesn’t have that feature). If you’re accepting category ids directly from external input or they might not exist for some other reason, you’d want to use a custom validation or change, depending on when you want to do the validation. With Ets lookups by id are very cheap, so it could be done in a validation. Normally anything that interacts with other resources we suggest using a change and a before_action hook to ensure that it only happens once when the action is submitted.

Also, if you use manage_relationship it will do this automatically.

1 Like