Search code examples
elixirecto

inserting multiple changesets in single transaction


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


Solution

  • Use MyRepo.transaction/2.

    MyRepo.transaction(fn ->
      Enum.each(changesets, &MyRepo.update!(&1, []))
    end)