2013-04-26 15 views
0

我有一個User模型,與Publication模型的關係爲has_many :through。反過來Publication模型具有has_many :through關係AuthorRails:協會未被發現;也許你拼錯了嗎?

class User < ActiveRecord::Base 
    has_many :library_publications, :dependent => :destroy, :class_name => "Library::Publication" 
    has_many :publications, :through => :library_publications 
end 

class Library::Publication < ActiveRecord::Base 
    belongs_to :publication 
    belongs_to :user 
end 

class Publication < PublicationBase 
    has_many :library_publications, :dependent => :destroy, :class_name => "Library::Publication" 
    has_many :users, :through => :library_publications 
    has_many :publication_contributions, :dependent => :destroy, :class_name => "Publication::Contribution" 
    has_many :authors, :through => :publication_contributions 
end 

class Author < AuthorBase 
    has_many :publication_contributions, :dependent => :destroy, :class_name => "Publication::Contribution" 
    has_many :publications, :through => :publication_contributions 
end 

class Publication::Contribution < Publication::ContributionBase 
    belongs_to :publication, :class_name => "Publication" 
    belongs_to :author, :class_name => "Author" 
end 

據我所知,所有的關聯被正確寫入。然而,當我嘗試從用戶eagerload作者:

@user.library_publications.includes(:publication => [:authors]) 

我得到這個錯誤:

Association named 'authors' was not found; perhaps you misspelled it? 

什麼可能的原因呢?

+0

我想你在這裏有一個錯字:'class Publication :: Contribution MurifoX 2013-04-26 17:11:24

+0

好的眼睛。我應該解釋一下。 'Publication :: ContributionBase'是一個STI類。在這個例子中還有一些其他的。雖然STI可能以某種方式干擾協會? – nullnullnull 2013-04-26 17:30:03

+0

這就是我想要的。但我還不確定。 – MurifoX 2013-04-26 17:31:26

回答

2

經過一番實驗,我發現publication的所有關聯都被破壞了。這導致我尋找更大的問題,最終我發現這個問題是由名稱空間中的一個連接表引起的,Library::Publication。當我將它重新命名時,publication的協會再次開始工作。

雖然我不確定爲什麼會發生這種情況。如果有人有解釋,請分享。