2012-10-25 89 views
0

我有以下型号和协会:协会通过的has_many和多属于

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定期。是用户和歌手/专辑之间创建has_and_belongs_to_many关联的最有效选择吗?

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

回答

2

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

+0

哇。脑屁。谢谢 – mrabin