[英]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.