Custom Ecto Type and additional parameters

Is it possible to pass additional parameters to a custom Ecto Type for example:

field :foo, :my_custom_ecto_type, some_additional_parameter.

My use case is trying to restrict a string value to some specific choices which I’d like to pass when I define the field e.g.

field :foo, :choices, ['cheese', 'ham', 'mustard']

I couldn’t find anything in the Ecto docs but wondered if I’d missed anything.

cheers

Dave

1 Like

The Ecto.Type behaviour doesn’t have callbacks that take those options as an argument. They are only used by the Ecto.Schema.field/3 macro.

I think the idea behind this is that types are really only there to perform data casting and loading (i. e. from DB data type to Elixir and vice versa) and not for validation.

And what you’re trying to do here seems more like an attempt to validate or constrain the possible values of a field. This is easily achieved with changesets, so you don’t even need to implement a custom type :slight_smile:

2 Likes

Ah, thank you. I’ve obviously misunderstood the use of Ecto.Type. I’ll look at changesets for my solution. Cheers.

1 Like