See update below
I want to add an existing track to an existing playlist but i am not sure how to approach this.
I have a
FYI - Models pasted below
I am assuming I need to write a function that will:
listen for a click event on a track
capture track_id
Ask to choose a playlist
display existing playlists
listen for click event on desired playlist
capture playlist_id
add track_id and playlist_id into Join Table
Then I should be able to navigate to the playlist SHOW Page and see the track that was added.
At the moment I am going to attempt rendering a simple form dropdown showing playlists on each track and adding a create method in my playlist_tracks controller.
But if anyone has a better idea or a link to a great resource, I would appreciate it. Will update this post if I progress
----- Models -----
Playlist Model
class Playlist < ApplicationRecord
has_many :playlist_tracks
has_many :tracks, through: :playlist_tracks
has_many :tags, through: :playlist_tags
belongs_to :user
validates :playlist_title, presence: true, length: { in: 1..20 }
validates :playlist_description, presence: true, length: { in: 10..60 }
has_one_attached :photo
end
Tracks model
class Track < ApplicationRecord
belongs_to :album
belongs_to :user
has_many :playlist_tracks
has_many :playlists, through: :playlist_tracks
has_many :tags, through: :tags_tracks
validates :title, presence: true, length: { in: 1..20 }
validates :description, presence: true, length: { in: 10..60 }
has_one_attached :photo
has_one_attached :track
end
PlaylistTrack Model
class PlaylistTrack < ApplicationRecord
belongs_to :track
belongs_to :playlist
end
UPDATE
I managed to get some help from a mentor. We decided the first easiest route to take was to include a simple form on each track card with a dropdown menu containing collection of playlists.
Form and controller below
Form
<%= simple_form_for @playlist_track, url: playlist_tracks_path, method: :post do |f| %>
<%= f.association :playlist, :collection => Playlist.all, label_method: :playlist_title %>
<%= f.input :track_id, as: :hidden, input_html: { value: track.id } %>
<%= f.submit "Create" %>
<% end %>
Controller
class PlaylistTracksController < ApplicationController
def create
@playlist_track = PlaylistTrack.new(playlist_track_params)
if @playlist_track.save!
redirect_to station_index_path
else
render 'new'
end
end
private
def playlist_track_params
params.require(:playlist_track).permit(:track_id, :playlist_id)
end
end
I can now add a track to an existing playlist :)