質問編集履歴

1

更新

2019/08/15 05:39

投稿

miiichat
miiichat

スコア72

test CHANGED
File without changes
test CHANGED
@@ -47,3 +47,149 @@
47
47
 
48
48
 
49
49
  あと投稿とコメントはテーブルを分けたほうがいいですか?
50
+
51
+
52
+
53
+ ###追記
54
+
55
+ ```
56
+
57
+ class Post < ApplicationRecord
58
+
59
+
60
+
61
+ has_many :comments, class_name: "Post", foreign_key: parent_id
62
+
63
+ belongs_to :post, optional: true, foreign_key: parent_id
64
+
65
+ end
66
+
67
+
68
+
69
+ ```
70
+
71
+ ```
72
+
73
+ sqlite> .schema posts
74
+
75
+ 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"
76
+
77
+ FOREIGN KEY ("user_id")
78
+
79
+ REFERENCES "users" ("id")
80
+
81
+ );
82
+
83
+ CREATE INDEX "index_posts_on_parent_id" ON "posts" ("parent_id");
84
+
85
+ CREATE INDEX "index_posts_on_user_id" ON "posts" ("user_id");
86
+
87
+ ```
88
+
89
+ ```
90
+
91
+ class CreatePosts < ActiveRecord::Migration[5.1]
92
+
93
+ def change
94
+
95
+ create_table :posts do |t|
96
+
97
+ t.string :title
98
+
99
+ t.text :body
100
+
101
+ t.integer :parent_id
102
+
103
+ t.references :user, foreign_key: true
104
+
105
+ t.timestamps
106
+
107
+ end
108
+
109
+ add_index :posts, :parent_id
110
+
111
+ end
112
+
113
+ end
114
+
115
+
116
+
117
+ ```
118
+
119
+ ```
120
+
121
+ class PostsController < ApplicationController
122
+
123
+
124
+
125
+ def index
126
+
127
+ end
128
+
129
+
130
+
131
+ def new
132
+
133
+ @post = Post.new
134
+
135
+ end
136
+
137
+
138
+
139
+ def create
140
+
141
+ end
142
+
143
+
144
+
145
+ def show
146
+
147
+ end
148
+
149
+ end
150
+
151
+ ```
152
+
153
+ ```
154
+
155
+ Rails.application.routes.draw do
156
+
157
+ devise_for :users, controllers: {
158
+
159
+
160
+
161
+
162
+
163
+
164
+
165
+ resources :posts
166
+
167
+ end
168
+
169
+ ```
170
+
171
+ ```
172
+
173
+ <%= form_for(@post) do |f| %>
174
+
175
+ <div class="field">
176
+
177
+ <%= f.label :title %>
178
+
179
+ <%= f.text_field :title %>
180
+
181
+
182
+
183
+ <%= f.label :body %>
184
+
185
+ <%= f.text_field :body %>
186
+
187
+
188
+
189
+ <%= f.submit "投稿" %>
190
+
191
+ </div>
192
+
193
+ <% end %>
194
+
195
+ ```