【问题标题】:rails how many foreign keys a table should haverails 一个表应该有多少个外键
【发布时间】:2016-03-21 21:46:47
【问题描述】:

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

我的问题是 post_replies 应该添加多少外键?我将始终仅在post index page 上显示它们,并且将使用format_js 添加新回复。 post_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

【问题讨论】:

    标签: ruby-on-rails activerecord foreign-keys schema relational-database


    【解决方案1】:

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

    【讨论】:

    • toddmetheny,请在 Elux91 的回答下查看我的评论
    • 你的路线在我看来很好——你有什么具体问题吗?
    • 是的,我不确定是否需要将post_replies 嵌套到post_comments 中。而且我也不确定是否必须将post_comments 嵌套到posts
    • 我认为您实际上也不需要嵌套,因为您只使用创建、更新、删除...嵌套不应该是必要的,但也不应该伤害任何东西。
    【解决方案2】:

    我认为你应该命名PostReplyCommentReply,因为这是对评论的回复,而不是直接对帖子的回复。

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

    这应该可以正常工作。

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

    【讨论】:

    • 路线呢?我只需要:create:destroy:update。在这种情况下,您将如何组织?
    • 你不需要索引路由来获取帖子的 cmets 吗?如果您只有创建、销毁和更新,那么您实际上没有任何操作可以为您提供帖子、cmets。
    • 我不需要它,因为 cmets 仅显示在 posts#index 页面上(post_replies 也会如此),我可以简单地调用 post.post_comments。但是例如,对于创建post_comment,必须识别post,所以我将它路由到它之下。现在我想我需要在post_comment 下路由post_replies
    • 确保您需要与 PostReply 相同的 CommentReply 路由。在您的示例路线中,没有用于显示或索引的路线,这让我感到困惑
    • 那么我现在对路线的处理似乎还不错?
    猜你喜欢
    • 2021-08-17
    • 1970-01-01
    • 2023-04-07
    • 2017-06-07
    • 2019-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多