質問編集履歴
1
更新
title
CHANGED
File without changes
|
body
CHANGED
@@ -22,4 +22,77 @@
|
|
22
22
|
みたいな感じで。
|
23
23
|
|
24
24
|
|
25
|
-
あと投稿とコメントはテーブルを分けたほうがいいですか?
|
25
|
+
あと投稿とコメントはテーブルを分けたほうがいいですか?
|
26
|
+
|
27
|
+
###追記
|
28
|
+
```
|
29
|
+
class Post < ApplicationRecord
|
30
|
+
|
31
|
+
has_many :comments, class_name: "Post", foreign_key: parent_id
|
32
|
+
belongs_to :post, optional: true, foreign_key: parent_id
|
33
|
+
end
|
34
|
+
|
35
|
+
```
|
36
|
+
```
|
37
|
+
sqlite> .schema posts
|
38
|
+
CREATE TABLE "posts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "title" varchar, "body" text, "parent_id" integer, "user_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, CONSTRAINT "fk_rails_5b5ddfd518"
|
39
|
+
FOREIGN KEY ("user_id")
|
40
|
+
REFERENCES "users" ("id")
|
41
|
+
);
|
42
|
+
CREATE INDEX "index_posts_on_parent_id" ON "posts" ("parent_id");
|
43
|
+
CREATE INDEX "index_posts_on_user_id" ON "posts" ("user_id");
|
44
|
+
```
|
45
|
+
```
|
46
|
+
class CreatePosts < ActiveRecord::Migration[5.1]
|
47
|
+
def change
|
48
|
+
create_table :posts do |t|
|
49
|
+
t.string :title
|
50
|
+
t.text :body
|
51
|
+
t.integer :parent_id
|
52
|
+
t.references :user, foreign_key: true
|
53
|
+
t.timestamps
|
54
|
+
end
|
55
|
+
add_index :posts, :parent_id
|
56
|
+
end
|
57
|
+
end
|
58
|
+
|
59
|
+
```
|
60
|
+
```
|
61
|
+
class PostsController < ApplicationController
|
62
|
+
|
63
|
+
def index
|
64
|
+
end
|
65
|
+
|
66
|
+
def new
|
67
|
+
@post = Post.new
|
68
|
+
end
|
69
|
+
|
70
|
+
def create
|
71
|
+
end
|
72
|
+
|
73
|
+
def show
|
74
|
+
end
|
75
|
+
end
|
76
|
+
```
|
77
|
+
```
|
78
|
+
Rails.application.routes.draw do
|
79
|
+
devise_for :users, controllers: {
|
80
|
+
・
|
81
|
+
・
|
82
|
+
・
|
83
|
+
resources :posts
|
84
|
+
end
|
85
|
+
```
|
86
|
+
```
|
87
|
+
<%= form_for(@post) do |f| %>
|
88
|
+
<div class="field">
|
89
|
+
<%= f.label :title %>
|
90
|
+
<%= f.text_field :title %>
|
91
|
+
|
92
|
+
<%= f.label :body %>
|
93
|
+
<%= f.text_field :body %>
|
94
|
+
|
95
|
+
<%= f.submit "投稿" %>
|
96
|
+
</div>
|
97
|
+
<% end %>
|
98
|
+
```
|