質問編集履歴

1

postsコントローラのコードを全て記載致しました

2020/03/20 04:45

投稿

ckr
ckr

スコア23

test CHANGED
File without changes
test CHANGED
@@ -8,7 +8,43 @@
8
8
 
9
9
  ```postsコントローラ
10
10
 
11
+ class PostsController < ApplicationController
12
+
13
+ before_action :authenticate_user!
14
+
15
+ before_action :set_post, only: %i(show destroy)
16
+
17
+
18
+
19
+
20
+
21
+ def index
22
+
23
+ @posts = Post.all.includes(:photos, :user).order('created_at DESC')
24
+
25
+ end
26
+
27
+
28
+
29
+ def show
30
+
31
+ @post = Post.find_by(id: params[:id])
32
+
33
+ end
34
+
35
+
36
+
37
+ def new
38
+
39
+ @post = Post.new
40
+
41
+ @post.photos.build
42
+
43
+ end
44
+
45
+
46
+
11
- def create
47
+ def create
12
48
 
13
49
  @post = Post.new(post_params)
14
50
 
@@ -29,6 +65,48 @@
29
65
  end
30
66
 
31
67
  end
68
+
69
+
70
+
71
+
72
+
73
+ def destroy
74
+
75
+ if @post.user == current_user
76
+
77
+ flash[:notice] = "投稿が削除されました" if @post.destroy
78
+
79
+ else
80
+
81
+ flash[:alert] = "投稿の削除に失敗しました"
82
+
83
+ end
84
+
85
+ redirect_to root_path
86
+
87
+ end
88
+
89
+
90
+
91
+ private
92
+
93
+ def post_params
94
+
95
+ params.require(:post).permit(:caption, photos_attributes: [:image]).merge(user_id: current_user.id)
96
+
97
+ end
98
+
99
+
100
+
101
+ def set_post
102
+
103
+ @post =Post.find_by(id: params[:id])
104
+
105
+ end
106
+
107
+ end
108
+
109
+
32
110
 
33
111
 
34
112