在类似的应用程序,以计算器,我建设,我想决定什么关系我的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) 我在Rails中创建了一个类似StackOverflow的网站,但我不确定问题上的投票是否有必要存储在数据库的单独表中.
是否有任何理由将数据分开?
或者我可以将投票作为单个总和存储在问题表的字段中吗?
基于StackOverflow 数据转储,似乎SO将问题和答案表示为单个表 - 帖子.
但是,一个问题有一个标题,一个正文和标签相关联,而答案只有一个正文.至少对我而言,这表明它们非常独特,应该是独立的表格.
此外,我不喜欢写"and type='question'"我的SQL.
这些是有道理的吗?
或者是否有充分的理由将问题和答案放在同一张表中?
我正在考虑以下数据库结构,但我不确定哪种类型的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)