【发布时间】:2011-05-05 20:13:53
【问题描述】:
有时说唱歌曲有不止一位艺术家。例如,Nicki Minaj's "Roman's Revenge" 以 Eminem 为特色,因此在 Rap Genius 目录中显示为“Nicki Minaj (Ft. Eminem) – Roman's Revenge”。
在 Rap Genius 中,我通过具有以下属性的 performances 连接模型为精选艺术家建模:
song_idartist_id-
role(“主要”或“特色”)
所以:
-
在
artist.rb:has_many :songs, :through => :performances -
在
song.rb:has_many :artists, :through => :performances
在song.rb:
def primary_artists
performances.select{|p| p.role == 'primary'}.map(&:artist).compact
end
def featured_artists
performances.select{|p| p.role == 'featured'}.map(&:artist).compact
end
# from the user's perspective there's only one primary artist
def primary_artist
primary_artists.first
end
问题是如何实现Song#primary_artist=和Song#featured_artists=。现在我正在这样做,这是错误的:
def primary_artist=(artist)
return if artist.blank?
Performance.song_id_eq(id).role_eq('primary').destroy_all
performances.build(:artist => artist, :role => 'primary')
end
这是错误的原因是这种方法会在现场销毁所有现有的主要艺术家,但只有在保存歌曲时才会创建替换的主要艺术家。所以,如果歌曲保存失败,它的主要艺术家将被删除。
这样做的正确方法是什么?我们希望只有在歌曲保存成功时才删除旧的主要艺术家,所以一个想法是:
def primary_artist=(artist)
return if artist.blank?
#Performance.song_id_eq(id).role_eq('primary').destroy_all
@performances_to_destroy << Performance.song_id_eq(id).role_eq('primary')
performances.build(:artist => artist, :role => 'primary')
end
def after_save
@performances_to_destroy.each(&:destroy)
end
但这似乎仍然有点令人困惑/骇人听闻。
【问题讨论】:
-
我不明白您为什么要将用户看到的内容限制为一位主要艺术家。如果您只显示所有相关的艺术家,您的问题不会消失吗?
-
不——尽管我现在意识到我的问题的核心比上面的要简单。见stackoverflow.com/questions/4111345/…
标签: ruby-on-rails activerecord model modeling