简体   繁体   English

通过has_many和multiple属于的关联

[英]association through has_many and multiple belongs to

I've got the following models and associations: 我有以下模型和协会:

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

I need to be able to call user.albums and user.artists on a regular basis. 我需要能够定期调用user.albums和user.artists。 Is the most efficient option to create has_and_belongs_to_many associations between User and Artist/Album ? 是否是在用户和艺术家/专辑之间创建has_and_belongs_to_many关联的最有效选项?

It seems like there should be a better way but I haven't been able to find anything yet. 似乎应该有一个更好的方法,但我还没有找到任何东西。

You could just use has_many :albums, :through => :songs on the user object. 您可以在用户对象上使用has_many:albums,:through =>:歌曲。 Arel(AR) will automatically create the joins for you resulting in one query and will only fetch the albums related to the songs belonging to the User. Arel(AR)会自动为您创建连接,从而产生一个查询,并且只会获取与属于用户的歌曲相关的相册。 The same goes for the artists on the User object. User对象上的艺术家也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM