In my Phoenix app I have the following schemas:
defmodule TattooBackend.Accounts.Account do
schema "accounts" do
field :email, :string
field :crypted_password, :string
field :password, :string, virtual: true
field :password_confirmation, :string, virtual: true
has_one :studio, Studio
timestamps()
end
end
defmodule TattooBackend.Accounts.Studio do
schema "studios" do
field :name, :string
belongs_to :account, Account
timestamps()
end
end
Now I’m trying to write code for inserting Account and Studio to the database in one transaction. I’m using Ecto.Multi for doing that. My code looks like this:
multi = Multi.new |>
Multi.insert(:account, Account.changeset(%Account{}, %{email: "test@email.com", password: "password", password_confirmation: "password"})) |>
Multi.run(:studio, fn %{account: account} ->
studio_changeset = Studio.changeset(%Studio{}, %{name: "test", account_id: account.id})
Repo.insert(studio_changeset)
end)
Repo.transaction(multi)
This code works perfectly fine, but I’m wondering if there is any place to make it better. I’m still pretty new to Elixir so I want to know if something can be done in better way. Is using Ecto.Multi the only one way of doing it? Maybe this can be done in another way?