[英]Rails: ActiveRecord has_many association not working
I'm a bit new to Rails Active Record associations. 我对Rails Active Record协会有点新鲜。 I've tried to set up a relationship, but I get ActiveRecord error when I try to retrieve data.
我试图建立一种关系,但是当我尝试检索数据时,我收到ActiveRecord错误。 Did I associate my models incorrectly?
我是否错误地关联了我的模型?
User has many Uploads, which has many UserGraphs: 用户有很多上传,其中有许多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
I want to get all of a user's uploads, and all of a user's graphs. 我希望得到所有用户的上传内容以及所有用户的图表。 The 2nd line doesn't work in rails console and gives an error
第二行在rails控制台中不起作用并出错
@user = User.find(1)
@uploads = @user.uploads
The error: 错误:
ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :user_graphs in model User
Extra Credit: 额外信用:
If Users have Uploads that have UserGraphs... shouldn't it be has_many :uploads
and has_many :user_graphs, through :uploads
? 如果用户拥有具有UserGraphs的上传...不应该是
has_many :uploads
和has_many :user_graphs, through :uploads
?
Add 加
has_many :user_graphs
to the User
and Upload
classes. 到
User
和Upload
类。
The :through option defines a second association on top of this one. :through选项定义了第二个关联。
You didn't tell Rails that you have a user_graphs
association on User
, only an uploads
association. 您没有告诉Rails您在
User
上有user_graphs
关联,只有uploads
关联。 So when Rails goes to follow the user_graphs
association on uploads
, it can't find it. 因此,当Rails在
uploads
时遵循user_graphs
关联时,它无法找到它。
So, you need add the user_graphs
association. 因此,您需要添加
user_graphs
关联。 Your models should look like this: 您的模型应如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.