What's the difference between required: true on cast_assoc and validate_required?

What’s the difference in behaviour of required between these uses?

cast_assoc(:author, required: true)
# vs this
validate_required(:author_id)
1 Like

Generally speaking, first one allows passing author as a struct. Therefore, cast_assoc calls AuthorSchema.changeset, validates their params, and allows us to insert new structure

And second one allows passing author as an id to existing struct.

1 Like

In some cases the primary key also might not yet be known (and therefore not exist) while you can already use cast_assoc with the required option to provide feedback to users.

1 Like