Hi, guys
I’m trying to insert many to many relation. Example is from José Valim - Wats new in Ecto 2.0 book.
Here is my implementation (copy):
schema "resources" do
field :url, :string
field :status_code, :integer
field :hash, :string
field :size, :integer
field :headers, {:map, :string}
field :response_time, :integer
belongs_to :mirror, Mirror
many_to_many :anchors, Anchor, join_through: "resources_anchor"
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> Ecto.Changeset.put_assoc(:anchors, insert_and_get_all(params.anchors))
end
defp insert_and_get_all([]), do: []
defp insert_and_get_all(anchors) do
hashes = Enum.map(anchors, &(&1[:hash]))
Repo.insert_all(Anchor, anchors, on_conflict: :nothing)
Repo.all(from a in Anchor, where: a.hash in ^hashes)
end
When I try to insert record via changeset I got error:
** (FunctionClauseError) no function clause matching in Ecto.Changeset.put_assoc/4
anchors: #Ecto.Association.NotLoaded<association :anchors is not loaded>
No record inserted in “resources”. Records inserted only in “anchor”. When I remove put_assoc record is inserted in “resources” as well.