Validate_inclusion with dynamic enum

Hello,

I want to validates a value among possible values with validate_inclusion but I’m stuck.

My use case is an avatar generation system, layer by layer. An avatar is defined by a pack (Dragon Ball, Among Us…) and many layers (body, hat, pants…). Let’s say that you chose the Dragon ball pack that only has 3 bodies while the Among Us pack has 10. I need the enum argument of validates_inclusion(:body, enum) to depend on the pack.

Is it possible? How could I implement that?

Thanks!

1 Like

Is the chosen pack somewhere in the changeset?

If yes then with fetch_field you can get the pack, and from that find the right enum to pass in the validation function.

Welcome here !

Hi Lud! Thank for your reply.

The pack is indeed in the changeset.

How would you pass the right enum to validate_inclusion since it expects (as I understand it at least) a static enum.

I would love to pass a function to validate_inclusion that receives the changeset and returns an enum.

I dont think the enum has to be static. I think you can pass any valid enumerable.

So something like that should work:

  def changeset(changeset) do
    changeset
    |> cast(...)
    |> validate_required(...)
    |> validate_parts()
  end

  defp validate_parts(changeset) do
    pack = fetch_field!(changeset, :pack)
    
    changeset
    |> validate_inclusion(:body, Packs.parts_for(pack, :body))
    |> validate_inclusion(:pants, Packs.parts_for(pack, :pants))
  end
1 Like

It works pefectly, thanks!

1 Like