0

我有以下模型和关联:

class User < ActiveRecord::Base   
    has_and_belongs_to_many :songs
end

class Song < ActiveRecord::Base 
    has_and_belongs_to_many :users
    belongs_to :album
    delegate :artist, :to => :album, :allow_nil => true
end

class Album < ActiveRecord::Base
    has_many :songs
    belongs_to :artist
end

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

我需要能够定期调用 user.albums 和 user.artists。在 User 和 Artist/Album 之间创建 has_and_belongs_to_many 关联是最有效的选择吗?

似乎应该有更好的方法,但我还没有找到任何东西。

4

1 回答 1

2

您可以在用户对象上使用 has_many :albums, :through => :songs 。Arel(AR) 将自动为您创建连接,从而产生一个查询,并且只会获取与属于用户的歌曲相关的专辑。User 对象上的艺术家也是如此。

于 2012-10-25T16:32:59.823 回答