我想开发一个博客应用程序。用户可以在其中创建一个帖子并对其进行评论。一个帖子可以有许多来自用户的评论,它应该属于用户。同样,评论应该属于用户和博客。因此,我可以识别哪个评论属于哪个帖子,以及哪个用户对post发表了评论。
因此,我在模型之间建立了如下关联:
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模型写这样的东西
belongs_to :author, class_name: "User", foreign_key: "user_id"迁移文件将是什么样子?我正在寻求你的建议和帮助。是否有更好的方法将这些模型联系起来?
您的帮助将不胜感激!
发布于 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返回与此注释关联的帖子
通过这样做:
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
endhttps://stackoverflow.com/questions/73355224
复制相似问题