2013-12-09 144 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 –