在类似的应用程序,以计算器,我建设,我想决定什么关系我的Questions
,Answers
和Comments
表应该有.
我可以拥有Questions
并且Answers
都由一张桌子代表Posts
.
这将允许Comments
有一个外键Posts
.
但是,如果Questions
并且Answers
是单独的表,那么Comments
这些表中应该有什么关系呢?
更新:尽管所选答案建议使用类表继承方法,这似乎是数据库术语中的最佳方法,但Rails ORM不支持此选项.因此,在Rails中,我的模型必须使用单表继承,并且可能如下所示:
class Post < ActiveRecord::Base
end
class Question < Post
has_many :answers, :foreign_key => :parent_id
has_many :comments, :foreign_key => :parent_id
end
class Answer < Post
belongs_to :question, :foreign_key => :parent_id
has_many :comments, :foreign_key => :parent_id
end
class Comment < Post
belongs_to :question, :foreign_key => :parent_id
belongs_to :answer, :foreign_key => :parent_id
end
class CreatePosts …
Run Code Online (Sandbox Code Playgroud) 例如,给定3个表:
并假设我们要执行
设置架构以实施这些约束的最佳方法是什么?
我为postgres提供了一个可能的答案,我对postgres和Oracle的解决方案特别感兴趣,但也有兴趣查看其他RDBMS的解决方案
编辑
作为参考,以下答案/评论中的SO问题解决了类似的问题: