小编Cha*_*e K的帖子

在StackOverflow克隆中,"注释"表与"问题与解答"之间应该有什么关系?

在类似的应用程序,以计算器,我建设,我想决定什么关系我的Questions,AnswersComments表应该有.

我可以拥有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)

database database-design polymorphic-associations

12
推荐指数
1
解决办法
2876
查看次数

在像StackOverflow这样的网站中,问题及其投票应该是单独的表吗?

我在Rails中创建了一个类似StackOverflow的网站,但我不确定问题上的投票是否有必要存储在数据库的单独表中.

是否有任何理由将数据分开?

或者我可以将投票作为单个总和存储在问题表的字段中吗?

sql database database-design

5
推荐指数
2
解决办法
331
查看次数

在StackOverflow克隆中,问题和答案是否可以作为单独的表?

基于StackOverflow 数据转储,似乎SO将问题和答案表示为单个表 - 帖子.

但是,一个问题有一个标题,一个正文和标签相关联,而答案只有一个正文.至少对我而言,这表明它们非常独特,应该是独立的表格.

此外,我不喜欢写"and type='question'"我的SQL.

这些是有道理的吗?

或者是否有充分的理由将问题和答案放在同一张表中?

database database-design

5
推荐指数
1
解决办法
297
查看次数

什么类型的Rails模型关系最适合聚合键+多个外键?

我正在考虑以下数据库结构,但我不确定哪种类型的Rails模型关系会支持我定义的数据库密钥.任何人都可以建议这在Rails中如何运作?

Posts
id
post_type -- must be 'Q' or 'A'
author
date
content
UNIQUE KEY (post_id, post_type) -- to support foreign keys

Questions
id
post_id
post_type -- must be 'Q'
FOREIGN KEY (post_id, post_type) REFERENCES Posts(post_id, post_type)

Answers    
id
post_id
post_type -- must be 'A'
question_id
FOREIGN KEY (post_id, post_type) REFERENCES Posts(post_id, post_type)
FOREIGN KEY (question_id) REFERENCES Questions(post_id)

Comments    
id
post_id
author
date
content
FOREIGN KEY (post_id) REFERENCES Posts(post_id)
Run Code Online (Sandbox Code Playgroud)

上面的草图将转换为以下实现:

CREATE TABLE Posts (
  post_id     SERIAL PRIMARY KEY,
  post_type   CHAR(1), …
Run Code Online (Sandbox Code Playgroud)

model ruby-on-rails

0
推荐指数
1
解决办法
1060
查看次数