私が構築している StackOverflow に似たアプリケーションで、 my と table の関係を決定しようとし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 < ActiveRecord::Migration
def self.up
create_table :posts do |t|
t.string :type
t.string :author
t.text :content
t.integer :parent_id
t.timestamps
end
end
def self.down
drop_table :posts
end
end
CREATE TABLE "posts" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"type" varchar(255),
"author" varchar(255),
"content" text,
"parent_id" integer,
"created_at" datetime,
"updated_at" datetime
);