How to put_assoc if assoc already exists and its send from API


I have article schema

schema "articles" do
  field :title, :string
  field :url, :string
  belongs_to :media, Media, on_replace: :nilify


And I want to add association to media that already exists and its loaded with API so In my changeset I use:

def changeset(%Article{} = article, attrs) do
  |> cast(attrs, [:title, :url])
  |> unique_constraint(:url)
  |> validate_required([:title, :url])
  |> put_assoc(:media,  attrs["media"])

attrs["media"] is map with id and all other fields but It creates a new association it dosnt associate it with existing one.

I got it to work with |> put_assoc(:media Gaby.Library.get_media!(attrs["media"]["id"]))
But I dont want to load something from database if I already have ID …

If you don’t have the structs of your associations you’re probably looking for cast_assoc.

I don’t have it, but I think cast_assoc can only create a new media it cant use existing one?

Nope, you might want to reread the docs on the function. Just like put_assoc it does consider any existing id fields in the params to determine if things need to be created/updated or removed.

Okay thank you, I will try it :slight_smile: