繁体   English   中英

rails一个表应该有多少个外键

[英]rails how many foreign keys a table should have

我有一个rails4应用程序。 我有下面的架构,将增加post_replies表,将belong_to :post_commentpost_commenthas_many :post_replies 评论中的回复将始终属于给定的评论。

我的问题是应该在post_replies中添加多少外键? 我将始终只在post index page上显示它们,并且将使用format_js添加新的回复。 post_reply belongs_to post_comment post_reply肯定,但是我也应该同时使用belongs_to :userbelongs_to :post

当前架构:

class User < ActiveRecord::Base
  has_many :posts
  has_many :post_comments, through: :posts
end

class Post < ActiveRecord::Base
  has_many :post_comments
  belongs_to :user
end

class PostComment < ActiveRecord::Base
  belongs_to :post
  belongs_to :user
end

计划架构:

class PostReply < ActiveRecord::Base
  belongs_to :post_comment #this is needed for sure
  belongs_to :post #do i need this?
  belongs_To :user #and this?
end

路线:

#current:

resources :posts do
  resources :post_comments, only: [:create, :update, :destroy], module: :posts
end

#and planning to add:

resources :post_comments, only: [] do 
  resources :post_repiles, only: [:create, :update, :destroy], module: :posts
end

它应该属于User但如果它已经属于post_comment则不需要属于该帖子,因为您可以通过该模型访问post。

我想你应该命名PostReply CommentReply ,因为它是直接对评论的回覆,而不是职位。

如果您已经有评论ID,则不需要保存post_id,因为评论已经与帖子有关系。

这应该工作得很好。

class CommentReply < ActiveRecord::Base
  belongs_to :post_comment
  belongs_To :user 
end

暂无
暂无

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

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