Is there any way to check if I provided unknown parameters to an Ecto changeset?

I ran into an issue today where I made a subtle typo in a params map which was then fed to an update changeset. The cast function in the changeset dutifully filtered out the unknown param, so no changes were made to the database.

Since the input params for my update changesets are all coming from my code rather than untrusted input, any unknown params going into cast are definitely a code error on my part, and it could help with diagnosing a few difficult-to-track-down bugs if I could check if any unexpected params were encountered when building a changeset (and thus filtered out).

Is there any way to check for that?

I had to do this last week, and I couldn’t find anything within Changeset API. Look at this issue.

I handled it like this; Once done with cast, make sure that changeset.params is as expected, and if there’s any unexpected keys use Changeset.add_error to add an error to the changeset.

Since you’re concern is to catch typos, I think you can use String.bag_distance to compare the unknown param to the whitelisted params and suggest a fix in the error’s message.

In general, for changesets, Ecto.Changeset.cast/4 is for handling outside, user-provided data that needs processing before it can be attached to the schema. Ecto.Changeset.change/2 and Ecto.Changeset.put_change/2 are for handling application-provided data that doesn’t need processing and where errors (like wrong keys) are programmer errors and thus, should raise exceptions.


change/2 looks perfect for this, thank you!