从专辑中查找特定类型的所有歌曲



基本模型是这样定义的:

class Song    
  belongs_to :album  
end
class Album  
  has_many :songs, dependent: :destroy  
  belongs_to :genre  
end

现在我想找到genre_id=10的专辑中的所有歌曲,我该怎么做?

.songs关联只作用于单个Album对象。

您可以使用has_many :through关联。查看Rails指南了解详细信息。

在你的例子中,你所需要做的就是像这样定义Genre类:
class Genre
  has_many :albums
  has_many :songs, through: :albums
end

可以在Genre对象上调用songs:

Genre.find(10).songs

编辑

如果你想要更多类型和歌曲之间的联系,这里有一个解决方案:

class Genre
  has_many :albums
  has_many :artists
  has_many :album_songs, through: :albums, source: :song
  has_many :artist_songs, through: :artists, source: :song
end

你可以这样写:

Genre.find(10).album_songs
Genre.find(10).artist_songs

May看起来有点奇怪,但是你可以给它们起一个合适的名字。

最新更新