【发布时间】:2011-10-21 16:26:36
【问题描述】:
大约一个小时前,我问了一个关于 Rails 协会的问题:
Question on Proper Associations in Rails
这个问题的公认答案让我更深入地思考关系,我想向 SO 社区介绍这种情况。
我之前的问题使用诗人、诗歌和印刷作为模型...对于这个问题,让我们使用音乐行业:
模型是:
- 艺术家
- 专辑
- 歌曲
- 类型
以下陈述被认为是正确的:
- 一张专辑可以有多个艺术家 - 即 Metallica 和 Pantera 发布一张圣诞专辑
- 一首歌曲可以属于多张专辑 - 例如,Yellow Submarine 出现在原始专辑以及披头士乐队的多张“Greatest hits”专辑中
- 一首歌曲也可以有多个与专辑艺术家不同的“特色”艺术家 - 即 Snoop Dogg 拥有这张专辑,但创作了一首以 Harry Connick Jr. 为主角的歌曲。或者一个更好的例子是当 DJ 发行一张专辑时这些歌曲是由其他艺术家创作的。
- 艺术家、专辑和歌曲都可以归类为多种/不同的流派 - 即 Brian Setzer Orchestra 被归类为“Swing”,他们的一张专辑可能是“Swing, Rockabilly”,而该专辑中的一首歌曲可能是“跳蓝调”。
在深入研究这个问题时,我立即看到 Artist & Genre 等模型可以“重用”。我们不想多次保存艺术家的信息——例如,如果我们有一首歌曲,其中既有主要艺术家,也有特色艺术家,两位艺术家的信息都应该存在于 DB 的“艺术家”表中。
此外,在查看“特色”艺术家方面(声明 #2)时,我们似乎有一个附加属性应该在关联中——类似于“特色”标志。
这就是我认为应该如何建立关联——以及我的帖子的顶点......这是对的,我怎样才能让它变得更好?
class Artist < ActiveRecord::Base
has_and_belongs_to_many :albums
has_and_belongs_to_many :genres
has_many :featurings
has_many :features, :through => :featurings, :conditions => "featured = true"
end
class Album < ActiveRecord::Base
has_and_belongs_to_many :artists
has_and_belongs_to_many :songs
has_many :featurings
has_many :featured_artists, :through => :featurings, :conditions => "featured = true"
end
class Song < ActiveRecord::Base
has_and_belongs_to_many :genres
has_many :artists
has_many :featurings
has_many :featured_artists, :through => :featurings, :conditions => "featured = true"
end
class Genre < ActiveRecord::Base
has_and_belongs_to_many :artists
has_and_belongs_to_many :songs
end
class Featurings < ActiveRecord::Base
# the db table for this class should have a "featured" boolean.
belongs_to :artist
belongs_to :album
belongs_to :song
end
像往常一样,非常感谢那些花时间阅读并提供意见的人!非常感谢!
【问题讨论】:
标签: ruby-on-rails activerecord associations has-many has-many-through