gpt4 book ai didi

ruby - 如何拥有允许重复的有序模型关联

转载 作者:太空宇宙 更新时间:2023-11-03 16:54:09 25 4
gpt4 key购买 nike

我有两个模型,Song 和 Show。节目是歌曲的有序列表,其中可以多次列出同一首歌曲。

也就是说,在 Show 的某处应该有一个有序数组(或散列或任何东西),它可以包含 Song1、Song2、Song1、Song3 并允许重新排序、插入或从该数组中删除。

我不知道如何使用 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

最佳答案

连接表的想法是正确的:

class Song < ActiveRecord::Base
attr_accessible :title
has_many :playlist_items
has_many :shows, :through => :playlist_items
end

class PlaylistItem < ActiveRecord::Base
belongs_to :shows #foreign_key show_id
belongs_to :songs #foreign_key song_id
end

class Show < ActiveRecord::Base
attr_accessible :date
has_many :playlist_items
has_many :songs, :through => :playlist_items
end

然后你可以做类似user.playlist_items.create :song => Song.last

关于ruby - 如何拥有允许重复的有序模型关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713698/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com