Rails Model for Playlist that can contain tracks and albums using polymorphism

Posted by philk on Stack Overflow See other posts from Stack Overflow or by philk
Published on 2010-03-22T17:38:31Z Indexed on 2010/03/22 17:41 UTC
Read the original article Hit count: 225

I struggle to find a model how to store a playlist with different type of items on it in Rails.

Consider I have

class Track
end

class Album
  has_many :tracks
end

class PlaylistItem
  belongs_to :playable
  belongs_to :playlist
end

class Playable
  belongs_to :playable, :polymorph => true
end

class Playlist
   has_many :playlist_items
end

I think I can use a polymorphic model "Playable" here since the Playlist can contain Tracks, Albums and maybe in the future also Movies.

Also I would like to use STI for Track and Albums since they share some common attributes like title and length but also have totally different attributes.

I modeled it like described here but it does not work. Anybody any idea how to model a Playlist that can contain many items of different kind?

© Stack Overflow or respective owner

Related posts about rails

Related posts about polymorphic