【问题标题】:Rails many to many relationship and remote relationshipRails 多对多关系和远程关系
【发布时间】:2012-02-08 00:37:05
【问题描述】:

假设我们在 rails 中有专辑、艺术家和歌曲模型。

专辑中:

class Album < ActiveRecord::Base
  has_many :artist_album
  has_many :artist, :through => :artist_album
  has_many :song

在专辑中:

class ArtistAlbum < ActiveRecord::Base
  belongs_to :album
  belongs_to :artist
end

在歌曲中:

class Song < ActiveRecord::Base
  has_many :artist_song
  has_many :artists, :through => :artist_song
  belongs_to :album

在艺术家中:

class Artist < ActiveRecord::Base
  has_many :artist_song
  has_many :song, :through => :artist_song

是否可以通过活动记录选择以下记录集:

  • 查找属于该艺术家的专辑

由于艺人依附于歌曲,而专辑只是歌曲的集合,艺人与专辑之间并无直接关系。

除了为相关艺术家选择属于每个专辑的每首歌曲

本质上是这样的:

SELECT albums.`name`
FROM artists INNER JOIN artist_songs ON artists.id = artist_songs.artist_id
     INNER JOIN songs ON songs.id = artist_songs.song_id
     INNER JOIN albums ON songs.album_id = albums.id

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    您是否缺少ArtistSong 模型?通常我们在has_many中使用复数形式,即has_many :artist_songs

    如果您有ArtistAlbum 加入模型,则无需转到Song 部分...如果您有以下设置,只需artist.albums

    class Artist < ActiveRecord::Base
      has_many :artist_albums
      has_many :albums, :through => :artist_albums
    end
    

    以下是您可以使用的,但不一定是必需的。

    class ArtistAlbum < ActiveRecord::Base
      belongs_to :artist
      belongs_to :album
    end
    
    class Album < ActiveRecord::Base
      has_many :artist_albums
      has_many :artist, :through => :artist_albums
    end
    

    【讨论】:

    • 谢谢,这让我开始使用基本模型!
    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多