簡體   English   中英

通過has_many和multiple屬於的關聯

[英]association through has_many and multiple belongs to

我有以下模型和協會:

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關聯的最有效選項?

似乎應該有一個更好的方法,但我還沒有找到任何東西。

您可以在用戶對象上使用has_many:albums,:through =>:歌曲。 Arel(AR)會自動為您創建連接,從而產生一個查詢,並且只會獲取與屬於用戶的歌曲相關的相冊。 User對象上的藝術家也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM