質問編集履歴

1

controllerの追記

2021/07/13 13:55

投稿

husqy
husqy

スコア2

test CHANGED
File without changes
test CHANGED
@@ -6,6 +6,10 @@
6
6
 
7
7
 
8
8
 
9
+ 用途の都合上、roadという名前にしていますが、機能的には投稿機能です。
10
+
11
+
12
+
9
13
  ### 前提・実現したいこと
10
14
 
11
15
  Ruby/Railsでいいね機能を実装しており、
@@ -294,6 +298,152 @@
294
298
 
295
299
 
296
300
 
301
+ ```Ruby
302
+
303
+ # roads_controller.rb
304
+
305
+
306
+
307
+ class RoadsController < ApplicationController
308
+
309
+
310
+
311
+ def index
312
+
313
+ @roads = Road.includes(:user, :likes).order(:created_at)
314
+
315
+ end
316
+
317
+
318
+
319
+ def show
320
+
321
+ @road = Road.find(params[:id])
322
+
323
+ @comments = @road.comments
324
+
325
+ @comment = Comment.new
326
+
327
+ end
328
+
329
+
330
+
331
+ def new
332
+
333
+ @road = Road.new
334
+
335
+ end
336
+
337
+
338
+
339
+ def create
340
+
341
+ @road = Road.create(road_params)
342
+
343
+ end
344
+
345
+
346
+
347
+ def edit
348
+
349
+ @road = Road.find(params[:id])
350
+
351
+ end
352
+
353
+
354
+
355
+ def update
356
+
357
+ road = Road.find(params[:id])
358
+
359
+ if params[:road][:road_image_ids]
360
+
361
+ params[:road][:road_image_ids].each do |road_image_id|
362
+
363
+ image = road.road_images.find(road_image_id)
364
+
365
+ image.purge
366
+
367
+ end
368
+
369
+ end
370
+
371
+ if road.update(road_params)
372
+
373
+ flash[:success] = "編集しました"
374
+
375
+ redirect_to roads_url
376
+
377
+ else
378
+
379
+ render :edit
380
+
381
+ end
382
+
383
+ end
384
+
385
+
386
+
387
+ def destroy
388
+
389
+ road = Road.find(params[:id])
390
+
391
+ road.destroy
392
+
393
+ end
394
+
395
+
396
+
397
+ private
398
+
399
+ def road_params
400
+
401
+ params.require(:road).permit(:title, :description, :latitude, :longitude, :content, road_images: []).merge(user_id: current_user.id)
402
+
403
+ end
404
+
405
+ end
406
+
407
+ ```
408
+
409
+
410
+
411
+ ```Ruby
412
+
413
+ # likes_controller.rb
414
+
415
+
416
+
417
+ class LikesController < ApplicationController
418
+
419
+ def create
420
+
421
+ current_user.likes.create!(road_id: params[:road_id])
422
+
423
+ @road = Road.find(params[:road_id])
424
+
425
+ end
426
+
427
+
428
+
429
+ def destroy
430
+
431
+
432
+
433
+ current_user.likes.find_by(road_id: params[:road_id]).destroy!
434
+
435
+ @road = Road.find(params[:road_id])
436
+
437
+ end
438
+
439
+ end
440
+
441
+
442
+
443
+ ```
444
+
445
+
446
+
297
447
  ### 試したこと
298
448
 
299
449