Redundant Ecto Schema definitions

While working on submitting a form, I ran into SQL errors when users submitted inputs that were too long for the columns.

In the schema macro, I declared the field like this:

field(:billing_country, :string, size: 2, null: false, default: "")

An in order to prevent a nasty truncation error from the database, I had to add a validation in the changeset like this:

|> validate_length(:billing_country, is: 2)

My question is – is this redundant? Shouldn’t the schema know how long its fields are without me having to specifically create a validation rule for it? Is there an easier way to define the schemas so I don’t have to list the field sizes and create a validate_length rule for each?

2 Likes

I don’t see any support for a size attribute in the field macro docs: https://hexdocs.pm/ecto/Ecto.Schema.html#field/3

Maybe you saw that in the migration add macro? But that of course is doing a completely different thing, it is specifying the size of the field in the underlying datastore.

2 Likes

Oh wow, yeah, I almost certainly copied that over from a migration.