{@thread.name}

wintermeyer
2023-01-23

wintermeyer:

How can I validate that for the following resource the level_id is not blank and that the Level resource for that level_id exists?

attributes do
  uuid_primary_key :id

  attribute :name, :string do
    allow_nil? false
    constraints max_length: 255
  end

  attribute :code, :string, constraints: [max_length: 3]

  attribute :slug, :string do
    allow_nil? false
    constraints max_length: 255
  end

  create_timestamp :inserted_at
  update_timestamp :updated_at
end

validations do
  validate present([:name, :slug])
end

relationships do
  belongs_to :level, Feriendaten.Geo.Level do
    attribute_writable? true
  end
end

ZachDaniel:

If you are using AshPostgres and the migration generator, that will be done for you.

ZachDaniel:

Well, the “ensuring it exists” part will be. Otherwise, add

belongs_to :level, Feriendaten.Geo.Level do
  attribute_writable? true
  allow_nil? false
end

ZachDaniel:

If you aren’t using AshPostgres, you may want to use manage_relationship(:level, type: :append_and_remove) to change the level because that will first look up the relevant level in the target resource.