Add an association between two unassociated Ecto records

Let’s say I have two tables, Category and Product, a Product belongs to a Category, a Category has many Products. Let’s say I inserted all categories in the database and I also insert a product record. I want to add an association between the product and the category records after both were created. How can I achieve that in Ecto?

I tried using put_assoc but it doesn’t seem to work.

I’m not even sure what is the order in which the records should be passed to put_assoc

I’ve tried both situations

changeset = product
         |> Ecto.Changeset.put_assoc(:category, category)

changeset = category 
         |> Ecto.Changeset.put_assoc(:products, product)

In both cases I get ** (MatchError) no match of right hand side value:
In the first case I also get the Product record struct being returned, In the second case I get a Category record back

From what I understand, put_changeset takes 3 mandatory parameters:

  1. changeset
  2. association name
  3. value to put in association

Is your first parameter a changeset already? I think it should be something like:

changeset = changeset |> Ecto.Changeset.put_assoc(:category, category)