質問編集履歴

1

修正

2021/09/15 09:54

投稿

naoki1128
naoki1128

スコア3

test CHANGED
File without changes
test CHANGED
@@ -150,6 +150,160 @@
150
150
 
151
151
 
152
152
 
153
+ ###Postコントローラー
154
+
155
+ ```ruby
156
+
157
+ class PostsController < ApplicationController
158
+
159
+ before_action :authenticate_user!
160
+
161
+
162
+
163
+ def index
164
+
165
+ @posts = Post.order("created_at DESC").limit(5)
166
+
167
+ end
168
+
169
+
170
+
171
+ def new
172
+
173
+ @post = Post.new
174
+
175
+ end
176
+
177
+
178
+
179
+ def create
180
+
181
+ @post = Post.create(post_params)
182
+
183
+ if @post.save
184
+
185
+ redirect_to root_path
186
+
187
+ else
188
+
189
+ render :new
190
+
191
+ end
192
+
193
+ end
194
+
195
+
196
+
197
+ def show
198
+
199
+ @post = Post.find(params[:id])
200
+
201
+ @comment = Comment.new
202
+
203
+ @comments = @post.comments.includes(:user)
204
+
205
+ end
206
+
207
+
208
+
209
+ def edit
210
+
211
+ @post = Post.find(params[:id])
212
+
213
+ end
214
+
215
+
216
+
217
+ def update
218
+
219
+ post = Post.find(params[:id])
220
+
221
+ post.update(post_params)
222
+
223
+ if post.save
224
+
225
+ redirect_to root_path
226
+
227
+ end
228
+
229
+ end
230
+
231
+
232
+
233
+ def destroy
234
+
235
+ post = Post.find(params[:id])
236
+
237
+ post.destroy
238
+
239
+ if post.destroy
240
+
241
+ redirect_to root_path
242
+
243
+ end
244
+
245
+ end
246
+
247
+
248
+
249
+ def prefecture
250
+
251
+ @post = Post.find_by(prefecture_id: params[:id])
252
+
253
+ @posts = Post.where(prefecture_id: params[:id]).order('created_at DESC')
254
+
255
+ end
256
+
257
+
258
+
259
+
260
+
261
+ private
262
+
263
+ def post_params
264
+
265
+ params.require(:post).permit(:title, :text, :prefecture_id, images: []).merge(user_id: current_user.id)
266
+
267
+ end
268
+
269
+ ```
270
+
271
+ ###Postモデル
272
+
273
+ ```ruby
274
+
275
+ class Post < ApplicationRecord
276
+
277
+ validates :title, presence: true
278
+
279
+ validates :text, presence: true
280
+
281
+ validates :prefecture_id, numericality: { other_than: 1 , message: "can't be blank"}
282
+
283
+ validates :images, presence: true
284
+
285
+
286
+
287
+ belongs_to :user
288
+
289
+ has_many :comments
290
+
291
+ has_many :likes, dependent: :destroy
292
+
293
+ has_many :liking_users, through: :likes, source: :user
294
+
295
+ has_many_attached :images
296
+
297
+ extend ActiveHash::Associations::ActiveRecordExtensions
298
+
299
+ belongs_to :prefecture
300
+
301
+ end
302
+
303
+ ```
304
+
305
+
306
+
153
307
  ### 試したこと
154
308
 
155
309