質問編集履歴
3
destroyアクションのコードを追加しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -19,6 +19,8 @@
|
|
19
19
|
|
20
20
|
↓comments_controller.rb
|
21
21
|
```
|
22
|
+
before_action :correct_user, only: [:destroy]
|
23
|
+
|
22
24
|
def create
|
23
25
|
@post = Post.find(params[:comment][:post_id])
|
24
26
|
@comment = @post.comments.build(comment_params)
|
@@ -31,6 +33,21 @@
|
|
31
33
|
render "posts/show"
|
32
34
|
end
|
33
35
|
end
|
36
|
+
|
37
|
+
def destroy
|
38
|
+
@comment.destroy
|
39
|
+
redirect_to post_url
|
40
|
+
end
|
41
|
+
|
42
|
+
|
43
|
+
private
|
44
|
+
|
45
|
+
def correct_user
|
46
|
+
@comment = current_user.comments.find_by(id: params[:id])
|
47
|
+
unless @comment
|
48
|
+
redirect_to post_url
|
49
|
+
end
|
50
|
+
end
|
34
51
|
```
|
35
52
|
|
36
53
|
↓posts_controller.rb
|
2
プロジェクトの構造とコントローラーのコードを書き足しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -1,5 +1,7 @@
|
|
1
|
-
投稿したコメントを削除できるようにしたいのですが、下記のコードを入れると `undefined method
|
1
|
+
投稿したコメントを削除できるようにしたいのですが、下記のコードを入れると `undefined method "image_url" for nil:NilClass` という別のところでエラーが出ます。
|
2
2
|
|
3
|
+
プロジェクトの構造としては、postsという写真投稿機能があり投稿された写真の詳細ページ(posts/show.html.erb)にコメント欄とコメント一覧を設置しています。
|
4
|
+
|
3
5
|
↓deleteのコード
|
4
6
|
```
|
5
7
|
<% if logged_in? && comment.user == current_user %>
|
@@ -15,6 +17,30 @@
|
|
15
17
|
</div>
|
16
18
|
```
|
17
19
|
|
20
|
+
↓comments_controller.rb
|
21
|
+
```
|
22
|
+
def create
|
23
|
+
@post = Post.find(params[:comment][:post_id])
|
24
|
+
@comment = @post.comments.build(comment_params)
|
25
|
+
@comment.user_id = current_user.id
|
26
|
+
if @comment.save
|
27
|
+
flash[:success] = 'コメントを投稿しました。'
|
28
|
+
redirect_to post_path(@post)
|
29
|
+
else
|
30
|
+
flash.now[:danger] = 'コメントを投稿できませんでした。'
|
31
|
+
render "posts/show"
|
32
|
+
end
|
33
|
+
end
|
34
|
+
```
|
35
|
+
|
36
|
+
↓posts_controller.rb
|
37
|
+
```
|
38
|
+
def show
|
39
|
+
@post = Post.find_by(id: params[:id])
|
40
|
+
@comment = Comment.new
|
41
|
+
end
|
42
|
+
```
|
43
|
+
|
18
44
|
よろしくお願いします。
|
19
45
|
|
20
46
|
|
1
追記しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -15,4 +15,8 @@
|
|
15
15
|
</div>
|
16
16
|
```
|
17
17
|
|
18
|
-
よろしくお願いします。
|
18
|
+
よろしくお願いします。
|
19
|
+
|
20
|
+
|
21
|
+
追記
|
22
|
+
コメント削除のリンクを押せば削除はできているようなのですが、そこから画面を再表示する際にエラーが出ているようです。
|