What is the best way to get a list of nested associations that have been, or will be, dropped?

I have a somewhat deeply nested form where each parent can have an arbitrary number of children. I’m using cast_assoc all the way down and passing it all to a single Repo.update. To delete children I’m setting a :delete virtual field (which I plan on changing to :sort_param/:drop_param soon). Some of these nested children have images associated with them, stored in the cloud. What is the best way to get a list of children that have been deleted?

My current solution I don’t like at all as it’s brittle, verbose, and hard to test, it was just quick to get working (and the first thing that came to find, for some reason). I have a phx-click on the delete buttons which add the path of the images to a paths_for_deletion array stored in state. After a successful update I just iterate and delete.

My other thoughts:

  • Walk the changeset tree and look for records marked for :delete. This is probably what I will end up changing it to.

  • Change the whole thing to a Ecto.Multi. This would be nice as I could perform the file deletion transactionally. The downside here is that that is a bit of a big change and it’s not the end of the world if a deletion fails (I’ll be notified anyway). Although, hmmmmm, maybe this is the way to go (d’oh).

Are there simpler ways I’m not thinking of?

Thanks!

EDIT: I said “delete buttons” up there when I meant “delete checkboxes”.

1 Like

Consider using Pathex

use Pathex, default_mod: :map
import Pathex.Lenses, only: [star: 0, matching: 1]
import Pathex.Combinator, only: [combine: 1]

lens =
  combine(fn lens ->
    matching(%{delete: true})
    ~> (alongside([path(:children) ~> star() ~> lens, path(:images)]) ||| matching(_))
    ||| (path(:children) ~> star() ~> lens)
  end)

item
|> Pathex.get(lens, [])
|> List.flatten()
# => [image1, image2, image3, image4]
1 Like

Oh shit, I’m actually already using Pathex in my project, it just didn’t occur to me to use it here as I have yet to wrap my head around the combinators. They currently still look really funky to me but I’ve been meaning to dig in so this is a good kick in the butt to finally do so. Awesome, thank you for the answer and for making the lib!

1 Like