【问题标题】:Problems modeling the concept of "featured artists" (on rap songs)建模“特色艺术家”概念的问题(在说唱歌曲中)
【发布时间】: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_id
  • artist_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


【解决方案1】:

一个稍微不同的想法,但在这里艺术家和歌曲之间有两种关系不是更简单和更清晰,即一首歌与艺术家之间的关系如下:

belongs_to :primary_artist,                :class_name => "Artist"
has_and_belongs_to_many :featured_artists, :class_name => "Artist"

【讨论】:

    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多