Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting multiple changesets in single transaction

Tags:

elixir

ecto

I have this bridge table :

schema "rooms_units" do
  field(:date_from, :utc_datetime)
  field(:date_to, :utc_datetime)
  belongs_to(:room, App.Room, primary_key: true)
  belongs_to(:unit, App..Unit)
end

I have list of maps coming from my endpoint and I made a list of changesets for each map.

[

#Ecto.Changeset<
 action: nil,
changes: %{
  date_from: #DateTime<2016-11-03 13:23:00Z>,
  date_to: #DateTime<2016-11-03 13:23:00Z>,
  room_id: 255,
  unit_id: 296
},
errors: [],
data: #App.RoomUnit<>,
valid?: true

#Ecto.Changeset<
action: nil,
changes: %{
  date_from: #DateTime<2016-11-03 13:23:00Z>,
  date_to: #DateTime<2016-11-03 13:23:00Z>,
  room_id: 256,
  unit_id: 296
},
errors: [],
data: #App.RoomUnit<>,
valid?: true
>
]

And I want to insert it in the rooms_units table in single transaction.

I tried Ecto.multi.insert_all. But it accepts list of maps not the changesets. Is there any other function than can help me with this

Thanks

like image 485
script Avatar asked Sep 15 '25 10:09

script


1 Answers

Use MyRepo.transaction/2.

MyRepo.transaction(fn ->
  Enum.each(changesets, &MyRepo.update!(&1, []))
end)
like image 151
Aleksei Matiushkin Avatar answered Sep 17 '25 20:09

Aleksei Matiushkin