質問編集履歴

5

文の修正

2021/07/08 03:15

投稿

aaa11
aaa11

スコア14

test CHANGED
File without changes
test CHANGED
@@ -22,9 +22,27 @@
22
22
 
23
23
 
24
24
 
25
-
26
-
27
- ```
25
+ ```
26
+
27
+
28
+
29
+ #gemファイル
30
+
31
+
32
+
33
+ ```
34
+
35
+ gem 'devise'
36
+
37
+ gem 'devise_token_auth'
38
+
39
+ gem 'rack-cors'
40
+
41
+ ```
42
+
43
+
44
+
45
+
28
46
 
29
47
  #Userモデル
30
48
 
@@ -220,6 +238,8 @@
220
238
 
221
239
  #Rails(TestsController)
222
240
 
241
+ controllers/api/v1/tests_controller.rb
242
+
223
243
  ```rails
224
244
 
225
245
  class Api::V1::TestsController < ApplicationController
@@ -260,6 +280,8 @@
260
280
 
261
281
  #SessionsController
262
282
 
283
+ controllers/api/v1/auth/sessions_controller.rb
284
+
263
285
  ```
264
286
 
265
287
  class Api::V1::Auth::SessionsController < ApplicationController

4

文の修正

2021/07/08 03:15

投稿

aaa11
aaa11

スコア14

test CHANGED
File without changes
test CHANGED
@@ -255,3 +255,73 @@
255
255
  end
256
256
 
257
257
  ```
258
+
259
+
260
+
261
+ #SessionsController
262
+
263
+ ```
264
+
265
+ class Api::V1::Auth::SessionsController < ApplicationController
266
+
267
+ def index
268
+
269
+ if current_api_v1_user
270
+
271
+ render json: { is_login: true, data: current_api_v1_user }
272
+
273
+ else
274
+
275
+ render json: { is_login: false, message: "ユーザーが存在しません" }
276
+
277
+ end
278
+
279
+ end
280
+
281
+ end
282
+
283
+ ```
284
+
285
+
286
+
287
+ #routes.rb
288
+
289
+ ```
290
+
291
+ Rails.application.routes.draw do
292
+
293
+ namespace :api do
294
+
295
+ namespace :v1 do
296
+
297
+ resources :tests, only: %i[index show new create edit ]
298
+
299
+
300
+
301
+ mount_devise_token_auth_for 'User', at: 'auth', controllers: {
302
+
303
+ registrations: 'api/v1/auth/registrations'
304
+
305
+ }
306
+
307
+
308
+
309
+ namespace :auth do
310
+
311
+ resources :sessions, only: %i[index]
312
+
313
+ end
314
+
315
+ end
316
+
317
+ end
318
+
319
+ end
320
+
321
+ ```
322
+
323
+
324
+
325
+ #reactからSessionsControllerを叩いたjsonのデータ
326
+
327
+ ![イメージ説明](363a2baf0d0f7c3d3d1e1b09be52e65e.png)

3

文の修正

2021/07/08 02:57

投稿

aaa11
aaa11

スコア14

test CHANGED
File without changes
test CHANGED
@@ -198,7 +198,25 @@
198
198
 
199
199
  ```
200
200
 
201
-
201
+ #app/controllers/application_controller.rb
202
+
203
+ ```rails
204
+
205
+ class ApplicationController < ActionController::Base
206
+
207
+ include DeviseTokenAuth::Concerns::SetUserByToken
208
+
209
+
210
+
211
+ skip_before_action :verify_authenticity_token
212
+
213
+ helper_method :current_user, :user_signed_in?
214
+
215
+
216
+
217
+ end
218
+
219
+ ```
202
220
 
203
221
  #Rails(TestsController)
204
222
 

2

文の修正

2021/07/04 21:36

投稿

aaa11
aaa11

スコア14

test CHANGED
@@ -1 +1 @@
1
- Rails API + React ログインしたユーザーのidが保存できません
1
+ Rails API + React + devise current_api_v1_user.id nil:NilClass
test CHANGED
@@ -1,6 +1,6 @@
1
1
  #実現したいこと
2
2
 
3
- Rails API + React + devise_token_authで登録したユーザーログインした時のsessionを利用て投稿する際にuser_idも登録させるようにしたいですが登録できません。アドバイスいただけないでしょうか。
3
+ Rails API + React + deviseでUserを登録しています。current_api_v1_user.idをTestテーブルに登録したいのすがNoMethodError (undefined method `id' for nil:NilClass):が出てまいuser_idが登録できません。アドバイスいただけないでしょうか。
4
4
 
5
5
 
6
6
 
@@ -22,7 +22,183 @@
22
22
 
23
23
 
24
24
 
25
+
26
+
25
- ```
27
+ ```
28
+
29
+ #Userモデル
30
+
31
+ db/migrate/devise_token_auth_create_users.rb
32
+
33
+ ```
34
+
35
+ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[6.1]
36
+
37
+ def change
38
+
39
+
40
+
41
+ create_table(:users) do |t|
42
+
43
+ ## Required
44
+
45
+ t.string :provider, :null => false, :default => "email"
46
+
47
+ t.string :uid, :null => false, :default => ""
48
+
49
+
50
+
51
+ ## Database authenticatable
52
+
53
+ t.string :encrypted_password, :null => false, :default => ""
54
+
55
+
56
+
57
+ ## Recoverable
58
+
59
+ t.string :reset_password_token
60
+
61
+ t.datetime :reset_password_sent_at
62
+
63
+ t.boolean :allow_password_change, :default => false
64
+
65
+
66
+
67
+ ## Rememberable
68
+
69
+ t.datetime :remember_created_at
70
+
71
+
72
+
73
+ ## Confirmable
74
+
75
+ t.string :confirmation_token
76
+
77
+ t.datetime :confirmed_at
78
+
79
+ t.datetime :confirmation_sent_at
80
+
81
+ t.string :unconfirmed_email # Only if using reconfirmable
82
+
83
+
84
+
85
+ ## Lockable
86
+
87
+ # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
88
+
89
+ # t.string :unlock_token # Only if unlock strategy is :email or :both
90
+
91
+ # t.datetime :locked_at
92
+
93
+
94
+
95
+ ## User Info
96
+
97
+ t.string :name
98
+
99
+ t.string :nickname
100
+
101
+ t.string :image
102
+
103
+ t.string :email
104
+
105
+ t.text :profile
106
+
107
+
108
+
109
+ ## Tokens
110
+
111
+ t.text :tokens
112
+
113
+
114
+
115
+ t.timestamps
116
+
117
+ end
118
+
119
+
120
+
121
+ add_index :users, :email, unique: true
122
+
123
+ add_index :users, [:uid, :provider], unique: true
124
+
125
+ add_index :users, :reset_password_token, unique: true
126
+
127
+ add_index :users, :confirmation_token, unique: true
128
+
129
+ # add_index :users, :unlock_token, unique: true
130
+
131
+ end
132
+
133
+ end
134
+
135
+
136
+
137
+ ```
138
+
139
+ #Testモデル
140
+
141
+ db/migrate/create_tests.rb
142
+
143
+ ```
144
+
145
+ class CreateTests < ActiveRecord::Migration[6.1]
146
+
147
+ def change
148
+
149
+ create_table :tests do |t|
150
+
151
+ t.integer :user_id
152
+
153
+ t.string :title
154
+
155
+ t.string :image
156
+
157
+ t.text :body
158
+
159
+ t.timestamps
160
+
161
+ end
162
+
163
+ end
164
+
165
+ end
166
+
167
+ ```
168
+
169
+
170
+
171
+ #app/models/user.rb
172
+
173
+ ```
174
+
175
+ class User < ActiveRecord::Base
176
+
177
+ devise :database_authenticatable, :registerable,
178
+
179
+ :recoverable, :rememberable, :validatable
180
+
181
+ include DeviseTokenAuth::Concerns::User
182
+
183
+ has_many :tests, dependent: :destroy
184
+
185
+ end
186
+
187
+ ```
188
+
189
+ #app/models/test.rb
190
+
191
+ ```
192
+
193
+ class Test < ApplicationRecord
194
+
195
+ belongs_to :user
196
+
197
+ end
198
+
199
+ ```
200
+
201
+
26
202
 
27
203
  #Rails(TestsController)
28
204
 
@@ -34,9 +210,7 @@
34
210
 
35
211
  @test = Test.new(test_params)
36
212
 
37
- @user = current_api_v1_user
213
+ @test.user_id = current_api_v1_user.id
38
-
39
- @test.user_id = @user.id
40
214
 
41
215
  if @test.save
42
216
 
@@ -63,329 +237,3 @@
63
237
  end
64
238
 
65
239
  ```
66
-
67
-
68
-
69
- #React(CreateTest.tsx)
70
-
71
- ```react
72
-
73
- import React, { useState, useContext, useEffect } from "react"
74
-
75
- import { useHistory } from "react-router-dom"
76
-
77
- import { AuthContext } from "App"
78
-
79
-
80
-
81
- import { makeStyles, Theme } from "@material-ui/core/styles"
82
-
83
- import TextField from "@material-ui/core/TextField"
84
-
85
- import Card from "@material-ui/core/Card"
86
-
87
- import CardContent from "@material-ui/core/CardContent"
88
-
89
- import CardHeader from "@material-ui/core/CardHeader"
90
-
91
- import Button from "@material-ui/core/Button"
92
-
93
-
94
-
95
- import { createTest } from "lib/api/test"
96
-
97
- import { CreateTestParams } from "interfaces/index"
98
-
99
-
100
-
101
- const useStyles = makeStyles((theme: Theme) => ({
102
-
103
- container: {
104
-
105
- marginTop: theme.spacing(6)
106
-
107
- },
108
-
109
- submitBtn: {
110
-
111
- marginTop: theme.spacing(2),
112
-
113
- flexGrow: 1,
114
-
115
- textTransform: "none"
116
-
117
- },
118
-
119
- header: {
120
-
121
- textAlign: "center"
122
-
123
- },
124
-
125
- card: {
126
-
127
- padding: theme.spacing(2),
128
-
129
- maxWidth: 400
130
-
131
- }
132
-
133
- }))
134
-
135
-
136
-
137
- const CreateTest: React.FC = () => {
138
-
139
- const { isSignedIn, currentUser } = useContext(AuthContext)
140
-
141
- const classes = useStyles()
142
-
143
- const histroy = useHistory()
144
-
145
-
146
-
147
- const [title, setTitle] = useState<string>("")
148
-
149
- const [image, setImage] = useState<string>("")
150
-
151
- const [body, setBody] = useState<string>("")
152
-
153
-
154
-
155
- const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => {
156
-
157
- e.preventDefault()
158
-
159
-
160
-
161
- const params: CreateTestParams = {
162
-
163
- title: title,
164
-
165
- image: image,
166
-
167
- body: body
168
-
169
- }
170
-
171
-
172
-
173
- try {
174
-
175
- const res = await createTest(params)
176
-
177
- console.log(res)
178
-
179
- if (res.status === 200) {
180
-
181
- console.log("登録完了")
182
-
183
- histroy.push("/mypage")
184
-
185
- } else {
186
-
187
- setAlertMessageOpen(true)
188
-
189
- }
190
-
191
- } catch (err) {
192
-
193
- console.log(err)
194
-
195
- setAlertMessageOpen(true)
196
-
197
- }
198
-
199
- }
200
-
201
-
202
-
203
- return (
204
-
205
- <>
206
-
207
- {
208
-
209
- isSignedIn && currentUser ? (
210
-
211
- <form noValidate autoComplete="off">
212
-
213
- <Card className={classes.card}>
214
-
215
- <CardHeader className={classes.header} title="Sign Up" />
216
-
217
- <CardContent>
218
-
219
- <TextField
220
-
221
- variant="outlined"
222
-
223
- required
224
-
225
- fullWidth
226
-
227
- label="title"
228
-
229
- value={title}
230
-
231
- margin="dense"
232
-
233
- onChange={event => setTitle(event.target.value)}
234
-
235
- />
236
-
237
-
238
-
239
- <input
240
-
241
- type="file"
242
-
243
- value={image}
244
-
245
- onChange={event => setImage(event.target.value)}
246
-
247
- >
248
-
249
- </input>
250
-
251
-
252
-
253
- <TextField
254
-
255
- variant="outlined"
256
-
257
- required
258
-
259
- fullWidth
260
-
261
- label="body"
262
-
263
- value={body}
264
-
265
- margin="dense"
266
-
267
- onChange={event => setBody(event.target.value)}
268
-
269
- />
270
-
271
-
272
-
273
- <Button
274
-
275
- type="submit"
276
-
277
- variant="contained"
278
-
279
- size="large"
280
-
281
- fullWidth
282
-
283
- color="default"
284
-
285
- disabled={!title || !body ? true : false}
286
-
287
- className={classes.submitBtn}
288
-
289
- onClick={handleSubmit}
290
-
291
- >
292
-
293
- 登録
294
-
295
- </Button>
296
-
297
- </CardContent>
298
-
299
- </Card>
300
-
301
- </form>
302
-
303
- ) : (
304
-
305
- <h1>Not signed in</h1>
306
-
307
- )
308
-
309
- }
310
-
311
- </>
312
-
313
- )
314
-
315
- }
316
-
317
-
318
-
319
- export default CreateTest
320
-
321
- ```
322
-
323
-
324
-
325
- #client.ts
326
-
327
- ```react
328
-
329
- import applyCaseMiddleware from "axios-case-converter"
330
-
331
- import axios from "axios"
332
-
333
-
334
-
335
- const options = {
336
-
337
- ignoreHeaders: true
338
-
339
- }
340
-
341
-
342
-
343
- const client = applyCaseMiddleware(axios.create({
344
-
345
- baseURL: "http://localhost:3001/api/v1"
346
-
347
- }), options)
348
-
349
-
350
-
351
- export default client
352
-
353
- ```
354
-
355
-
356
-
357
- #test.ts
358
-
359
- ```react
360
-
361
- import client from "lib/api/client"
362
-
363
- import { CreateTestParams } from "interfaces/index"
364
-
365
-
366
-
367
- export const createTest = (params: CreateTestParams) => {
368
-
369
- return client.post("/tests", params)
370
-
371
- }
372
-
373
- ```
374
-
375
-
376
-
377
- #interfaces/index.ts
378
-
379
- ```react
380
-
381
- export interface CreateTestParams {
382
-
383
- title: string
384
-
385
- image?: string
386
-
387
- body: string
388
-
389
- }
390
-
391
- ```

1

2021/07/04 20:05

投稿

aaa11
aaa11

スコア14

test CHANGED
@@ -1 +1 @@
1
- Rails API + React + devise_token_auth
1
+ Rails API + React ログインしたユーザーのidが保存できません
test CHANGED
File without changes