I’m just working through Programming Ecto.
I understand how I can add new many-to-many assocs with cast_assoc
or put_assoc
. But those work with the assoc as a whole. I just want to connect two exisiting records. There is no mention how to do that in the book and not in the Ecto documentation. Which I find odd.
In the book’s Music-DB example there is this table:
create table(:albums_genres) do
add(:album_id, references(:albums))
add(:genre_id, references(:genres))
end
end
and this schema:
schema "albums_genres" do
belongs_to(:albums, Album)
belongs_to(:genres, Genre)
end
To add a new genre to an album the “normal” way would be (preload required)
put_assoc(album_changeset, [new_genre | album.genres])
I thought I could just
%AlbumGenre{albums_id: album.id, genres_id: genre.id} |> Repo.insert()
But no:
** (Exqlite.Error) table albums_genres has no column named albums_id
…and album_id
is not in the Struct.
So this fix in the Schema: (EDIT: better fix: :albums
→ :album
, :genres
→ :genre
)
schema "albums_genres" do
belongs_to(:album, Album)
belongs_to(:genre, Genre)
end
And I can do
%AlbumGenre{album_id: portrait.id, genre_id: live.id} |> Repo.insert()
This seems such an common thing to do, yet Ecto and the documentation and the Standard-book seem to not want me to do that. Why? Is this evil somehow?