回答編集履歴

2

原因が判明したため追記

2020/01/15 08:21

投稿

shinoharat
shinoharat

スコア1676

test CHANGED
@@ -35,3 +35,115 @@
35
35
 
36
36
 
37
37
  comment_params ではなく、params がどういう状態になっているか確認してみてください。
38
+
39
+
40
+
41
+ --
42
+
43
+
44
+
45
+ (追記ここから)
46
+
47
+
48
+
49
+ params の確認ありがとうございます。
50
+
51
+ 原因が分かりました。
52
+
53
+
54
+
55
+ ## 解説
56
+
57
+
58
+
59
+ まずは、params に含まれているはずの text が comment_params で取得出来なかった理由について説明したいと思います。
60
+
61
+
62
+
63
+ 今の params の構造ですが、余分なデータを除くと以下のようになっています。
64
+
65
+ 「comment の中の text に値が入っている」という点がポイントです。
66
+
67
+
68
+
69
+ ```
70
+
71
+ {
72
+
73
+ "comment"=>{"text"=>"ccccc"},
74
+
75
+ "post_id"=>"5"
76
+
77
+ }
78
+
79
+ ```
80
+
81
+
82
+
83
+ 一方、現在のコードでは、一番上の階層に text がある前提で permit されています。
84
+
85
+
86
+
87
+ ```rb
88
+
89
+ def comment_params
90
+
91
+ # ↓ 本当は「comment の中の text」を permit しないといけないです
92
+
93
+ params.permit(:text, :post_id)
94
+
95
+ end
96
+
97
+ ```
98
+
99
+
100
+
101
+ params の直下に text というキーは存在しないため、当然値は nil になります。
102
+
103
+
104
+
105
+ ## 修正方法
106
+
107
+
108
+
109
+ まずは comment_params を以下のように修正します。
110
+
111
+
112
+
113
+ ```rb
114
+
115
+ def comment_params
116
+
117
+ # 「comment の中の text」を permit する。
118
+
119
+ params.require(:comment).permit(:text)
120
+
121
+ end
122
+
123
+ ```
124
+
125
+
126
+
127
+ これで text は無事に取れるようになるはずです。
128
+
129
+ しかし、今度は params 直下の post_id が取得できなくなってしまいました。
130
+
131
+ そこで、次に create アクションを以下のように修正します。
132
+
133
+
134
+
135
+ ```rb
136
+
137
+ def create
138
+
139
+ # post_id は直接 params[:post_id] のように指定する
140
+
141
+ Comment.create(text: comment_params[:text], post_id: params[:post_id], user_id: current_user.id)
142
+
143
+ end
144
+
145
+ ```
146
+
147
+
148
+
149
+ これで、 text も post_id もちゃんと読み取れるはずです。お試しください。

1

typo

2020/01/15 08:21

投稿

shinoharat
shinoharat

スコア1676

test CHANGED
@@ -8,7 +8,7 @@
8
8
 
9
9
 
10
10
 
11
- 怪しいのは CommentsController の comment_params の以下の処理かなと思います。
11
+ 怪しいのは CommentsController の comment_params の処理かなと思います。
12
12
 
13
13
 
14
14