rails table 应该有多少个外键

rails how many foreign keys a table should have

我有一个 Rails4 应用程序。我有下面的架构,将添加 post_replies table 将 belong_to :post_commentpost_commenthas_many :post_replies。评论下的回复将始终属于该评论。

我的问题是post_replies应该加多少个外键?我将始终只在 post index page 上显示它们,新回复将添加 format_jspost_reply belongs_to post_comment 当然可以,但我是否应该同时使用 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

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

我认为你应该命名为 PostReply CommentReply,因为它是对评论的回复,而不是直接对 post 的回复。

如果您已有评论 ID,则无需保存 post_id,因为该评论已与 post.

相关联

这应该可以正常工作。

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