Changeset.cast returning Ecto.CastError

Hey guys,

To sum up, I’m trying to get a default behaviour when trying to insert things. In my case, I’m trying to set a field is_deleted to false even if the user sets it to true.

I’m trying to accomplish it by using the Map.merge function just as follows:

def changeset(%Campaign{} = campaign, attrs) do
    new_campaign = Map.merge(attrs, %{is_deleted: false})

    campaign
    |> cast(new_campaign, [:name, :mailing, :is_deleted])
    |> changeset_cast
end

I’m getting this error:

(Ecto.CastError) expected params to be a map with atoms or string keys, got a map with mixed keys: %{:is_deleted => false, "is_deleted" => true, "mailing" => nil, "name" => nil}

I could just remove :is_deleted from the function, but I wanna use the same function to update as well.

Any idea how to deal with?

Thanks!

campaign
|> cast(new_campaign, [:name, :mailing])
|> put_change(:is_deleted, false)
|> changeset_cast

Thanks man, I wonder why I’m getting this error. Does you know?

Sure. It literally says it in the error message. You’re mixing atom and string keys (%{"some_key => _, :is_deleted => false}, which doesn’t seem to be supported by casts. It’s also in general not a good idea to do that even outside of ecto.

Right, but It should work with %{"is_deleted": false}, am I getting this wrong? I’m asking because it doesn’t work.

Thanks man

%{"is_deleted": false} is still a map with atom keys. String keys are not defined using colons, but like this: %{"is_deleted" => false}

1 Like

Got it. Thanks man :slight_smile: