Prevent a changeset from being added in case it has a true :delete field

I have schema A that has_many schema B,

  schema "a" do
    ...
    has_many :b, B, on_replace: :delete
  end

  ...
  def changeset(a, attrs) do
    comment
    ...
    |> cast_assoc(:b, with: &B.changeset/2)
  end

schema B has a virtual delete field

  schema "b" do
    ...
    field :delete, :boolean, virtual: true
  end

I don’t want to cast_assoc for every thing, I just want cast_assoc to check if B has a non-true :delete field before adding it to the changeset of A, or else not add it at all

Why not filter them out before?

…
def changeset(a, attrs) do
    attrs = Map.update(attrs, :b, Enum.reject(& &1.delete))
    comment
    ...
    |> cast_assoc(:b, with: &B.changeset/2)
 end

And because :b’s module has a changeset/2, I think you don’t even need the :with.

1 Like