简体   繁体   中英

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. Is the most efficient option to create has_and_belongs_to_many associations between User and Artist/Album ?

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. 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. The same goes for the artists on the User object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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