質問編集履歴
1
画像のコード化、新情報の追加
test
CHANGED
File without changes
|
test
CHANGED
@@ -1,26 +1,78 @@
|
|
1
1
|
|
2
2
|
独学でポートフォリオのSNSアプリを開発しています。
|
3
|
-
posts/show 内で投稿へのコメント機能を実装していたのですが、コメントフォームが空欄の状態で、Commentsコントローラーのcreateアクションを実行すると、(
|
3
|
+
posts/show 内で投稿へのコメント機能を実装していたのですが、コメントフォームが空欄の状態で、Commentsコントローラーのcreateアクションを実行すると、(図1)のようなエラーが発生しました。
|
4
4
|
|
5
|
-
(
|
5
|
+
(図2)の13行目を参照すると、Commentsコントローラー内から, Postsコントローラーのshowアクションをレンダリングする際に、postのkey(ID)が渡されていないことが原因だと考えました。
|
6
6
|
|
7
7
|
同じコントローラー内であれば、railsがshowアクションに渡すkeyを自動的に解釈すると理解しているのですが、コントローラーが異なる場合、どのようにコードすれば正しくレンダリングされるのでしょうか。
|
8
8
|
|
9
|
-
また、突貫工事として(
|
9
|
+
また、突貫工事として(図3)のようなリダイレクトではエラーを回避しました。
|
10
10
|
|
11
11
|
|
12
12
|
|
13
13
|
|
14
|
-
(
|
14
|
+
(図1)
|
15
15
|
![イメージ説明](https://ddjkaamml8q8x.cloudfront.net/questions/2022-08-22/8e31a3f0-1953-4e5d-9795-4e08fdd31fdc.png)
|
16
16
|
|
17
|
-
(
|
17
|
+
(図2)
|
18
|
+
```ここに言語を入力
|
19
|
+
class CommentsController < ApplicationController
|
20
|
+
|
21
|
+
def create
|
22
|
+
@post = Post.find(params[:post_id])
|
23
|
+
@comment = current_user.comments.new(comment_params)
|
24
|
+
if @comment.save
|
25
|
+
redirect_to request.referer, notice: "コメントを投稿しました。"
|
26
|
+
else
|
27
|
+
flash.now.alert = 'コメントの作成に失敗しました。'
|
28
|
+
render template: "posts/show", status: :unprocessable_entity
|
29
|
+
end
|
30
|
+
end
|
31
|
+
|
32
|
+
def edit
|
33
|
+
@post = Post.find(params[:post_id])
|
34
|
+
@comment = Comment.find(params[:id])
|
35
|
+
end
|
36
|
+
|
37
|
+
def update
|
38
|
+
@post = Post.find(params[:post_id])
|
39
|
+
@comment = Comment.find(params[:id])
|
40
|
+
if @comment.update(comment_params)
|
41
|
+
redirect_to post_path(@post), notice: "コメントを編集しました。"
|
42
|
+
else
|
43
|
+
flash.now.alert = "コメントの編集に失敗しました。"
|
44
|
+
render :edit, status: :unprocessable_entity
|
45
|
+
end
|
46
|
+
end
|
47
|
+
|
48
|
+
def destroy
|
49
|
+
@comment = Comment.find(params[:id])
|
50
|
+
@comment.destroy
|
51
|
+
redirect_to request.referer, notice: "コメントを削除しました。", status: :see_other
|
52
|
+
end
|
53
|
+
|
54
|
+
private
|
55
|
+
def comment_params
|
18
|
-
|
56
|
+
params.require(:comment).permit(:context, :reply_comment_id).merge(post_id: params[:post_id])
|
57
|
+
end
|
58
|
+
end
|
59
|
+
```
|
19
60
|
|
20
61
|
|
62
|
+
(図3)※変更したcreateアクション内のみ記述。
|
21
|
-
|
63
|
+
```
|
22
|
-
|
64
|
+
class CommentsController < ApplicationController
|
23
65
|
|
66
|
+
def create
|
67
|
+
@post = Post.find(params[:post_id])
|
68
|
+
@comment = current_user.comments.new(comment_params)
|
69
|
+
if @comment.save
|
70
|
+
redirect_to request.referer, notice: "コメントを投稿しました。"
|
71
|
+
else
|
72
|
+
redirect_to request.referer, notice: "コメントの作成に失敗しました。", status: :see_other
|
73
|
+
end
|
74
|
+
end
|
75
|
+
```
|
24
76
|
質問経験が浅く拙い文章ですが、ご教授いただけますと幸いです。
|
25
77
|
|
26
78
|
|