簡體   English   中英

如何通過3個模型的關聯來提供has_many?

[英]How to provide has_many through association through 3 models?

我希望有人已經經歷過。 請幫助我,我該如何解決這個問題:

class Article < ActiveRecord::Base
  belongs_to :author
  belongs_to :publisher
  has_one :address, :through => :publisher
end

class Author < ActiveRecord::Base
  has_many :articles
  has_many :addresses, :through => :articles, :source => :address
end

我嘗試獲取“作者”的“地址”,並且在控制台中收到此錯誤:

ActiveRecord::HasManyThroughSourceAssociationMacroError: Invalid source reflection macro :has_one :through for has_many :addresses, :through => :articles.  Use :source to specify the source reflection.

但是author.articles[0].address工作正常。

希望您能給我建議,我該如何解決。 謝謝。

AR不喜歡通過has_one獲取has_many 但是您可以使用Author上的此方法輕松獲取所有地址:

def addresses
  articles.map {|article| article.address }
end

此解決方案也適用於不同的關系類型。

例如User.registrations.join_table.periods

但是您-無法-在映射的內容上應用active_record方法。

例如user.periods(:order =>:date)例如user.periods.model等。

謝謝

暫無
暫無

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

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