I have two models Playlist
and Song
. The playlist has an ordered list of songs through a join table playlist_song_associations
with a position
attribute, e.g.
class Playlist < ApplicationRecord
has_many :playlist_song_associations, dependent: :destroy
has_many :songs, through: :playlist_song_associations
end
class Song < ApplicationRecord
has_many :playlist_song_associations, dependent: :destroy
has_many :playlists, through: :playlist_song_associations
end
class PlaylistSongAssociation < ApplicationRecord
belongs_to :playlist, touch: true
belongs_to :song
default_scope { order(position: :asc) }
end
Now I have an update controller method, where I do something like
playlist.songs = get_ordered_songs_from_params
And I want the associations to be ordered according to the order within the get_ordered_songs_from_params
array.
Is there a way to set this up, so that rails automagically sets the position
attribute on the associations?