Rails 多模型关联

发布于 2024-12-16 12:03:13 字数 978 浏览 3 评论 0原文

我有一个具有以下模型的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无悔心 2024-12-23 12:03:13

此设置应该适合您:

user.rb

has_many :versions, :foreign_key => 'creator_id'
has_many :questions, :through => :versions

version.rb

belongs_to :creator, :class_name => "User"
belongs_to :question, :class_name => "Post", :foreign_key => 'post_id'

post.rb

has_many :versions

现在您可以像这样访问问题:User .first.questions

This setup should work for you:

user.rb

has_many :versions, :foreign_key => 'creator_id'
has_many :questions, :through => :versions

version.rb

belongs_to :creator, :class_name => "User"
belongs_to :question, :class_name => "Post", :foreign_key => 'post_id'

post.rb

has_many :versions

Now you can access the questions like so: User.first.questions

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文