2013-12-09 118 views
3

我對Rails活動記錄關聯有點新。我嘗試建立關係,但是當我嘗試檢索數據時發生ActiveRecord錯誤。我錯誤地將模型關聯了嗎?Rails:ActiveRecord has_many協會不工作

用戶有很多上傳,其中有許多UserGraphs:

class User < ActiveRecord::Base 
    has_many :uploads, through: :user_graphs 
end 

class Upload < ActiveRecord::Base 
    has_many :users, through: :user_graphs 
end 

class UserGraph < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :upload 
end 

我希望得到所有用戶的上傳和用戶的圖形的所有。二號線不軌控制檯工作,並給出了一個錯誤

@user = User.find(1) 
@uploads = @user.uploads 

錯誤:

ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_graphs in model User 

附加題:

如果用戶擁有的UserGraphs上傳...不應該是has_many :uploadshas_many :user_graphs, through :uploads

回答

4

添加

has_many :user_graphs 

UserUpload類。

的:通過選項定義在這一個的頂部上的第二關聯。

+0

Thanks @tyler - should not it has_many:user_graphs,through:uploads?我是否在我的帖子代碼中將其顛倒過來? –

2

您沒有告訴Rails您在User上有user_graphs關聯,只有uploads關聯。所以當Rails去關注user_graphs關聯uploads時,它找不到它。

所以,你需要添加user_graphs關聯。你的模型應該是這樣的:

class User < ActiveRecord::Base 
    has_many :user_graphs      # <<< Add this! 
    has_many :uploads, through: :user_graphs 
end 

class Upload < ActiveRecord::Base 
    has_many :user_graphs      # <<< Add this! 
    has_many :users, through: :user_graphs 
end 

class UserGraph < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :upload 
end 
+0

謝謝@約翰!關於Rails實際上試圖做什麼的很好的回答:) –

+0

實際上得到了一個rails錯誤 - 現在我去了user_graphs。誤差約爲ActiveRecord的::協會:: CollectionProxy []> –

+0

圖表= User.find(1).uploads.user_graphs –