I have a problem with inserting associations when using :through. I have not been writing anything in Ecto or Phoenix for a quite a long time and spend few past hours trying to make it any without success.
I have 3 models:
defmodule Office.Client do
...
schema "clients" do
...
has_many :clients_phones, Office.Litigation.Schemas.ClientPhone
has_many :phones, through: [:clients_phones, :phone]
...
end
defmodule Office.Phone do
...
schema "phones" do
field :number, :string
end
def changeset(%Phone{} = phone, params \\ %{}) do
phone
|> cast(params, [:number])
|> validate_required([:number])
end
end
defmodule Office.ClientPhone do
...
schema "clients_phones" do
belongs_to :client, Office.Litigation.Schemas.Client
belongs_to :phone, Office.Litigation.Schemas.Phone
end
What I want to do is having a client_id = x, and number = xxxxxxxxx assosiate this number with client through.
I don’t know who should ClientPhone changeset look like, and I don’t know how a function taking client_id and number should look like. As I said i spent few hours on this, and having many errors I don’t understand mostly from cast_assoc
and put_assoc
I can do it like that:
client = Repo.get!(Client, 1)
phone = Repo.insert!(%Phone{number: "123"})
Repo.insert!(%ClientPhone{phone: phone, client: client})
But i don’t know how to do it using Repo.insert!(ClientPhone with not yet inserted phone number, and only client_id withouth selecting client from DB first)
in one go