Question

I'm trying to add acts_as_list to an existing playlists table in my database, which stores any playlists that my users might have created. The goal is to allow users to sort their own playlists.

This migration will set a default position for the playlists in the table, but the position will be set in a global context (for example, the position column will be ordered 1-500 for a table with 500 playlists in it):

class AddPositionToPlaylistsTable < ActiveRecord::Migration
  def self.up
    add_column  :playlists, :position, :integer
    Playlist.reset_column_information
    playlist = Playlist.find(:all, :order => "created_at ASC")

    playlist.each_with_index do |p, i|
      p.position = i+1
      p.save
    end

  end

  def self.down
    remove_column :playlists, :position
  end
end

This order would be problematic, because moving an item's position from 500 to 499 wouldn't necessarily reflect any change from the user's perspective (as they might have playlists that have a position of 50, 70, 100, and 500).

Instead, I want to set a position for each playlist in the table in a per-user context (for example, presuming each user has 5 playlists, the position column would have multiple instances of playlists ordered 1-5 for each user).

Is this possible, and if so, how would I modify my migration to accomplish this?

Was it helpful?

Solution

When updating your playlists position, you only take the user's playlists into account. So you should do it from the beginning. In your migration's up-method you could get all playlists per user and then increase the index like you did:

#....
User.all.each do |user|
  user_playlists = user.playlists(:order => "created_at ASC")

  user_playlists.each_with_index do |p, i|
    p.position = i+1
    p.save
  end
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top