Update one record and all its associated records with one value

I have a table A that has_many B and also A has_many C, through: B.

I am trying to set up a soft deletion system in Ecto where fetching a record from A from the DB and its associated Bs and Cs, I could update all at the same time A, its Bs, its Cs with one value : state : :deleted. (they each have a state column).

How can I do this ? I’ve tried looking at cast_assoc or put_assoc but I feel like it isn’t exactly what I am looking for.

Hope my explanation is clear, let me know if it isn’t, I’ll try to explain better.

Thanks! :smiley:

Edit : I’m not familiar with it but perhaps using Ecto.Multi could do the trick?

1 Like

I’d probably go for Multi as you suggested yourself. Something like:

|> Multi.update(:table_a, query_to_update_table_a_record)
|> Multi.update_all(:table_b, query_to_update_table_b_records)
|> Multi.update_all(:table_c, query_to_update_table_c_records)
|> YourApp.Repo.transaction()

Ecto.Multi is what you need. It’s easily one of the very best tools in the Elixir ecosystem. Learn it well and you’ll have a superpower. :wink: