繁体   English   中英

Ruby On Rails:数据库 model 关联

[英]Ruby On Rails: Database model Associations

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

因此,我在模型之间进行了如下关联

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 model 中添加一个user_id ,这样我就可以识别谁是 Post 的作者。

它会解决我的问题吗?如果我在model 后写这样的东西

belongs_to :author, class_name: "User", foreign_key: "user_id"

迁移文件的外观如何? 我正在寻找您的建议和帮助。 有没有更好的方法来关联这些模型?

您的帮助将不胜感激!

您提出的建议将起作用,但您的语法似乎落后了。

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

我希望@post.user返回“撰写此帖子的用户”,但您让@post.users返回“所有评论此帖子的用户”

我会争取这些方法:

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

  • @user.comments返回此用户创建的所有评论

  • @user.commented_posts返回此用户评论过的所有帖子

  • @post.user返回创建(“创作”)此帖子的用户

  • @post.comments返回与此帖子相关的所有评论

  • @post.commented_users返回对此帖子发表评论的所有用户

  • @comment.user返回创建此评论的用户

  • @comment.post返回与此评论关联的帖子

通过做这个:

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 :posts
  belongs_to :user # author
end

class Comment < ApplicationRecord
 belongs_to :post
 belongs_to :user # commentor
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM