Ecto.Changeset.cast *all* fields shortcut

Is it possible to denote that all fields in a schema are permitted in cast/4, other than:

schema
|> cast(params, __MODULE__.__schema__(:fields))

Maybe something like cast_all ?

1 Like

Permitting all fields is something explicitly not supported easily, as it’s easy to add something to a schema afterwards and not realizing it’s automatically casted as well. So you’d need to go with the code you already have there.

2 Likes

This allows casting :id which you basically never want. It also lets someone mess with the timestamps. There’s a reason it isn’t supported in a pretty fashion.

7 Likes

Perfectly clear, tnx!

By the way, I am implementing Absinthe at the moment, so there’s no messing with my models :wink:

I was hoping for this so debugging in IEx was easier. I’m gonna hack a gross function together in my .iex.exs file so no big deal, but that’s the use case I had.

In case it’s helpful to others, I put it as a gist: https://gist.github.com/FreedomBen/19bbe85182eefc03b0678b26ae0d1325

Here’s what it looks like right now:

#
# This module defines some handy functions for use in iex
#
defmodule DebugTools do
  @doc ~S"""
  Cast all the params provided here into an Ecto.Changeset.
  
  This defeats Ecto's whitelist approach so you should never use this in real code!
  It's intended as a debug tool for use in tests of IEx sessions.
  """
  def ecto_cast_all(data, params, opts \\ []),
    do: Ecto.Changeset.cast(data, params, Map.keys(params), opts)
end