Rails 多模型关联
我有一个具有以下模型的 Rails 应用程序:
User (id)
Version (id, post_id, creator_id)
Post (id)
到目前为止,设置如下:
User.rb:
has_many :versions
Version.rb:
belongs_to :creator, :class_name => "User"
belongs_to :post
Post.rb:
has_many :versions
现在我想将用户链接到他通过版本表拥有的帖子,并制作最糟糕的是,这种联系必须称为问题。我在想这样的事情:
添加到 User.rb:
has_many :questions, :class_name => "Post", :source => :post, :through => :versions
问题是这不起作用,而且可能不应该起作用,因为它不知道版本表中用户密钥的名称是什么。
错误信息:
SQLite3::SQLException:没有这样的列:versions.user_id:SELECT COUNT(*) FROM "posts" INNER JOIN "versions" ON "posts"."id" = "versions"."post_id" WHERE "versions" ."user_id" = 1
我不知所措,救命!
注意:唯一不起作用的关系是最后一个用户<==> posts
又名 users.questions
I have a rails application with the following Models:
User (id)
Version (id, post_id, creator_id)
Post (id)
So far setup is as follows:
User.rb:
has_many :versions
Version.rb:
belongs_to :creator, :class_name => "User"
belongs_to :post
Post.rb:
has_many :versions
Now i would like to link a user to the posts he has through the versions table, and to make it worst this connection must be called questions. I was thinking something like this:
Added to User.rb:
has_many :questions, :class_name => "Post", :source => :post, :through => :versions
Problem is this doesn't work and probably shouldn't since it doesn't know what the user key's name is in the versions table.
Error message:
SQLite3::SQLException: no such column: versions.user_id: SELECT COUNT(*) FROM "posts" INNER JOIN "versions" ON "posts"."id" = "versions"."post_id" WHERE "versions"."user_id" = 1
I'm at a loss, help!
Note: The only relationship that doesn't work is the final one users <==> posts
a.k.a users.questions
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此设置应该适合您:
user.rb
version.rb
post.rb
现在您可以像这样访问问题:
User .first.questions
This setup should work for you:
user.rb
version.rb
post.rb
Now you can access the questions like so:
User.first.questions