0

I would like to implement a drag and drop of a list of items in a playlist. Playlist contents are of different activerecord types. I need to store the position and persist it in the database and handle the ordering using acts_as_list. I'm not sure I'm building the associations correctly.

I built has_many_through relationships using a join table, but I'm not sure how to get acts_as_list to work with this configuration.

My models are like this:

class Playlist < ActiveRecord::Base

  belongs_to :group
  belongs_to :user

  has_many :links, through: :playlists_contents dependent: :destroy
  has_many :medias,  through: :playlists_contents dependent: :destroy
end

My migration for the join table looks like this:

class CreateJoinTable < ActiveRecord::Migration[5.0]
  def change
    create_table :contents_playlists do |t|
      t.belongs_to :link, index: true
      t.belongs_to :media, index: true
      t.belongs_to :playlist, index: true
    end
  end

I have this so far in my join table model:

class PlaylistsContents < ActiveRecord::Base

  default_scope -> { order(position: :asc) }

  default_scope :order => 'position'
  belongs_to :playlist
  belongs_to :link
  belongs_to :media
  acts_as_list :scope => :link
  acts_as_list :scope => :media

end

1 Answer 1

1

You'll need a position field in the contents_playlists (or playlists_contents - as the model is called PlaylistsContents?) table. You can add multiple scopes by using:

acts_as_list scope: [:playlist, :link, :media]

Edit: added :playlist

2
  • so I don't have to create a third polymorphic model called content that the other models inherit from that should be positionable?
    – Ayrad
    Commented Nov 21, 2018 at 9:11
  • 1
    No, and if you don't mind the types mixing, you can just scope by :playlist
    – lafeber
    Commented Nov 21, 2018 at 9:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.