How to use multiple changesets at the same page

Viewed 743

I have to update 3 tables at the same time. One page has 3 changesets.

If I post 3 chagnesets with form_for, how can I write code? The 3 tables are following.

---------
 members
---------
id
name

----------------
 member_details  
----------------
member_id
address
phone_no

--------------
 member_items
--------------
member_id
item_id

Or another way will be welcomed.

2 Answers

Assuming that you want the tables to be either all updated or not, this required a transaction. The perfect use-case for Ecto.Multi. There is the example that you might directly apply to your case.

To split incoming params to three sets, one would probably use Map.take/2.

I felt in a similar problem as you. You don't need 3 Changesets. What you need is an embedded_schema that contains the 3 top elements you're trying to insert. Then when you submit the form you can call each of the changesets corresponding to the element you're trying to insert. Finally you make use of Ecto.Multi or Repo.transaction in other to make this operation all fail or all succeed. Have a look at the top description (specifically the SignUp example) of the documentation of schema on how this works. https://hexdocs.pm/ecto/Ecto.Schema.html

Related