Song と Show の 2 つのモデルがあります。ショーは曲の順序付きリストであり、同じ曲を複数回リストすることができます。
つまり、Song1、Song2、Song1、Song3 を含む順序付き配列 (またはハッシュなど) が Show のどこかに存在し、その配列から並べ替え、挿入、または削除ができる必要があります。
これを ActiveRecord アソシエーションでモデル化する方法がわかりません。インデックス用の列を持つ特別な結合テーブルが必要だと思いますが、SQL を直接コーディングする以外に、Rails の関連付けでこれを行う方法はありますか?
私が今持っているいくつかのコード(ただし、正しく動作しません):
class Song < ActiveRecord::Base
attr_accessible :title
has_and_belongs_to_many :shows
end
class Show < ActiveRecord::Base
attr_accessible :date
has_and_belongs_to_many :songs
end
song1 = Song.create(title: 'Foo')
song2 = Song.create(title: 'Bar')
show1 = Show.create(date: 'Tomorrow')
show1.songs << song1 << song2 << song1
puts "show1 size = #{show1.songs.size}" # 3
show1.delete_at(0) # Should delete the first instance of song1, but leave the second instance
puts "show1 size = #{show1.songs.size}" # 2
show1.reload
puts "show1 size = #{show1.songs.size}" # 3 again, annoyingly
挿入は次のようになります。
show1.songs # Foo, Bar, Foo
song3 = Song.create(title: 'Baz')
show1.insert(1, song3)
show1.songs # Foo, Baz, Bar, Foo
並べ替えは (ちょっとした魔法で) 次のようになります。
show1.songs # Foo, Bar, Foo
show1.move_song_from(0, to: 1)
show1.songs # Bar, Foo, Foo