首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails:数据库模型关联

Rails:数据库模型关联
EN

Stack Overflow用户
提问于 2022-08-14 21:27:37
回答 1查看 36关注 0票数 0

我想开发一个博客应用程序。用户可以在其中创建一个帖子并对其进行评论。一个帖子可以有许多来自用户的评论,它应该属于用户。同样,评论应该属于用户和博客。因此,我可以识别哪个评论属于哪个帖子,以及哪个用户对post发表了评论。

因此,我在模型之间建立了如下关联:

代码语言:javascript
复制
class User < ApplicationRecord
   has_many :comments
   has_many :posts, through: :comments
end

class Post < ApplicationRecord
   has_many :comments
   has_many :users, through: :comments
end

class Comment < ApplicationRecord
   belongs_to :post
   belongs_to :user
end

现在,我的问题是如何识别哪个用户创建了这个帖子。我想在 Post 模型中添加一个,这样我就可以识别谁是Post的作者。

它能解决我的问题吗?,如果我用Post模型写这样的东西

代码语言:javascript
复制
belongs_to :author, class_name: "User", foreign_key: "user_id"

迁移文件将是什么样子?我正在寻求你的建议和帮助。是否有更好的方法将这些模型联系起来?

您的帮助将不胜感激!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-14 22:46:49

您建议的内容将有效,但您的语法似乎落后。

我希望@user.posts返回“该用户创建的帖子”,而不是“有此用户评论的帖子”。

我希望@post.user会返回“作者这个帖子的用户”,但是@post.users会返回“在这个帖子上评论的所有用户”。

我会为这些方法而努力:

  • @user.posts返回用户创建的所有帖子(“编写”)

  • @user.comments返回用户创建的所有注释

  • @user.commented_posts返回用户在

上评论的所有帖子

  • @post.user返回创建(“编写”)此文章的用户

  • @post.comments返回与本文

相关的所有注释

  • @post.commented_users返回在这个帖子

上评论过的所有用户

  • @comment.user返回创建此注释的用户

  • @comment.post返回与此注释

关联的帖子

通过这样做:

代码语言:javascript
复制
class User < ApplicationRecord
  has_many :posts # "authored" posts
  has_many :comments
  has_many :commented_posts, through: :comments, source: :post
end

class Post < ApplicationRecord
  has_many :comments
  belongs_to :user # author
  has_many :commented_users, through: :comments, source: :user
end

class Comment < ApplicationRecord
 belongs_to :post
 belongs_to :user # commentor
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73355224

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档