Hello,
I’m trying to implement playlists, using this answer from Stackoverflow as an example.
I created the tables playlists
, videos
and the join-table playlists_videos
to model playlists in the database and currently have a schema looking this.
schema "playlists" do
field :name, :string, null: false
belongs_to(:user, User)
many_to_many :videos, Video, join_through: "playlists_videos"
end
The problem with this is that the videos are not sorted when I preload :videos
. Would it be possible to define the association, so that the videos are loaded in the correct order?
I’m thinking that the query for fetching the videos in the correct order, for a given playlist, could look like this:
from p in Playlist,
join: pv in "playlists_videos", on: p.id == pv.playlist_id
join: v in Video, on: pv.video_id == v.id,
order_by: pv.order,
where: p.id == ^playlist_id,
select: v