I have the following:
schema "communications" do
belongs_to :recipient, Recipient
belongs_to :user, User
timestamps()
end
def changeset(communication, attrs) do
communication
|> cast(attrs, [:user_id, :recipient_id])
|> cast_assoc(:recipient)
end
Creating a communication
with a new Recipient
works:
attrs = %{
recipient: %{email: "NewRecipient@email.com", name: "New Recipient"},
user_id: user.id
}
|> Communications.create_communication()
=> {:ok, %Communication{}}
However, creating a new Communication
with an existing Recipient
does not.
attrs = %{
recipient: %{
id: recipient.id, # <-- Includes the ID
email: "existing@email.com",
name: "Existing Recipient"},
user_id: user.id
}
changeset(comm, attrs) =>
%{
recipient: #Ecto.Changeset<
action: :insert, # <-- ** action is :insert **
changes: %{email: "existing@email.com", name: "Existing Recipient"},
errors: [],
data: #Recipient<>,
valid?: true
>,
user_id: 12345
}
Based on the documentation:
If the parameter contains an ID and there is an associated child with such ID, the parameter data will be passed to
MyApp.Address.changeset/2
with the existing struct and become an update operation
It’s my understanding, then, that if I include the ID of the recipient, the recipient will get updated whenever I create a new communication. And yet, this isn’t happening.
I’m not entirely sure if I misread the documentation, but including an existing recipient’s ID should update the recipient based on my understanding. Instead, it appears Ecto is attempting to create a new recipient.
Any pointers on what I’m getting wrong? Much appreciated. Thank you