teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

5

文の修正

2021/07/08 03:15

投稿

aaa11
aaa11

スコア14

title CHANGED
File without changes
body CHANGED
@@ -10,8 +10,17 @@
10
10
 
11
11
  NoMethodError (undefined method `id' for nil:NilClass):
12
12
 
13
+ ```
13
14
 
15
+ #gemファイル
16
+
14
17
  ```
18
+ gem 'devise'
19
+ gem 'devise_token_auth'
20
+ gem 'rack-cors'
21
+ ```
22
+
23
+
15
24
  #Userモデル
16
25
  db/migrate/devise_token_auth_create_users.rb
17
26
  ```
@@ -109,6 +118,7 @@
109
118
  end
110
119
  ```
111
120
  #Rails(TestsController)
121
+ controllers/api/v1/tests_controller.rb
112
122
  ```rails
113
123
  class Api::V1::TestsController < ApplicationController
114
124
  def create
@@ -129,6 +139,7 @@
129
139
  ```
130
140
 
131
141
  #SessionsController
142
+ controllers/api/v1/auth/sessions_controller.rb
132
143
  ```
133
144
  class Api::V1::Auth::SessionsController < ApplicationController
134
145
  def index

4

文の修正

2021/07/08 03:15

投稿

aaa11
aaa11

スコア14

title CHANGED
File without changes
body CHANGED
@@ -126,4 +126,39 @@
126
126
  params.require(:test).permit(:title, :image, :body)
127
127
  end
128
128
  end
129
- ```
129
+ ```
130
+
131
+ #SessionsController
132
+ ```
133
+ class Api::V1::Auth::SessionsController < ApplicationController
134
+ def index
135
+ if current_api_v1_user
136
+ render json: { is_login: true, data: current_api_v1_user }
137
+ else
138
+ render json: { is_login: false, message: "ユーザーが存在しません" }
139
+ end
140
+ end
141
+ end
142
+ ```
143
+
144
+ #routes.rb
145
+ ```
146
+ Rails.application.routes.draw do
147
+ namespace :api do
148
+ namespace :v1 do
149
+ resources :tests, only: %i[index show new create edit ]
150
+
151
+ mount_devise_token_auth_for 'User', at: 'auth', controllers: {
152
+ registrations: 'api/v1/auth/registrations'
153
+ }
154
+
155
+ namespace :auth do
156
+ resources :sessions, only: %i[index]
157
+ end
158
+ end
159
+ end
160
+ end
161
+ ```
162
+
163
+ #reactからSessionsControllerを叩いたjsonのデータ
164
+ ![イメージ説明](363a2baf0d0f7c3d3d1e1b09be52e65e.png)

3

文の修正

2021/07/08 02:57

投稿

aaa11
aaa11

スコア14

title CHANGED
File without changes
body CHANGED
@@ -98,7 +98,16 @@
98
98
  belongs_to :user
99
99
  end
100
100
  ```
101
+ #app/controllers/application_controller.rb
102
+ ```rails
103
+ class ApplicationController < ActionController::Base
104
+ include DeviseTokenAuth::Concerns::SetUserByToken
105
+
106
+ skip_before_action :verify_authenticity_token
107
+ helper_method :current_user, :user_signed_in?
101
108
 
109
+ end
110
+ ```
102
111
  #Rails(TestsController)
103
112
  ```rails
104
113
  class Api::V1::TestsController < ApplicationController

2

文の修正

2021/07/04 21:36

投稿

aaa11
aaa11

スコア14

title CHANGED
@@ -1,1 +1,1 @@
1
- Rails API + React ログインしたユーザーのidが保存できません
1
+ Rails API + React + devise current_api_v1_user.id nil:NilClass
body CHANGED
@@ -1,5 +1,5 @@
1
1
  #実現したいこと
2
- Rails API + React + devise_token_authで登録したユーザーでログインした時のsessionを利用し投稿る際user_idも登録させるようにしたいですが登録できません。アドバイスいただけないでしょうか。
2
+ Rails API + React + deviseUserを登録していま。current_api_v1_user.idをTestテーブルに登録したいですがNoMethodError (undefined method `id' for nil:NilClass):が出てしまいuser_idが登録できません。アドバイスいただけないでしょうか。
3
3
 
4
4
  #エラー文
5
5
  ```
@@ -10,14 +10,101 @@
10
10
 
11
11
  NoMethodError (undefined method `id' for nil:NilClass):
12
12
 
13
+
13
14
  ```
15
+ #Userモデル
16
+ db/migrate/devise_token_auth_create_users.rb
17
+ ```
18
+ class DeviseTokenAuthCreateUsers < ActiveRecord::Migration[6.1]
19
+ def change
20
+
21
+ create_table(:users) do |t|
22
+ ## Required
23
+ t.string :provider, :null => false, :default => "email"
24
+ t.string :uid, :null => false, :default => ""
25
+
26
+ ## Database authenticatable
27
+ t.string :encrypted_password, :null => false, :default => ""
28
+
29
+ ## Recoverable
30
+ t.string :reset_password_token
31
+ t.datetime :reset_password_sent_at
32
+ t.boolean :allow_password_change, :default => false
33
+
34
+ ## Rememberable
35
+ t.datetime :remember_created_at
36
+
37
+ ## Confirmable
38
+ t.string :confirmation_token
39
+ t.datetime :confirmed_at
40
+ t.datetime :confirmation_sent_at
41
+ t.string :unconfirmed_email # Only if using reconfirmable
42
+
43
+ ## Lockable
44
+ # t.integer :failed_attempts, :default => 0, :null => false # Only if lock strategy is :failed_attempts
45
+ # t.string :unlock_token # Only if unlock strategy is :email or :both
46
+ # t.datetime :locked_at
47
+
48
+ ## User Info
49
+ t.string :name
50
+ t.string :nickname
51
+ t.string :image
52
+ t.string :email
53
+ t.text :profile
54
+
55
+ ## Tokens
56
+ t.text :tokens
57
+
58
+ t.timestamps
59
+ end
60
+
61
+ add_index :users, :email, unique: true
62
+ add_index :users, [:uid, :provider], unique: true
63
+ add_index :users, :reset_password_token, unique: true
64
+ add_index :users, :confirmation_token, unique: true
65
+ # add_index :users, :unlock_token, unique: true
66
+ end
67
+ end
68
+
69
+ ```
70
+ #Testモデル
71
+ db/migrate/create_tests.rb
72
+ ```
73
+ class CreateTests < ActiveRecord::Migration[6.1]
74
+ def change
75
+ create_table :tests do |t|
76
+ t.integer :user_id
77
+ t.string :title
78
+ t.string :image
79
+ t.text :body
80
+ t.timestamps
81
+ end
82
+ end
83
+ end
84
+ ```
85
+
86
+ #app/models/user.rb
87
+ ```
88
+ class User < ActiveRecord::Base
89
+ devise :database_authenticatable, :registerable,
90
+ :recoverable, :rememberable, :validatable
91
+ include DeviseTokenAuth::Concerns::User
92
+ has_many :tests, dependent: :destroy
93
+ end
94
+ ```
95
+ #app/models/test.rb
96
+ ```
97
+ class Test < ApplicationRecord
98
+ belongs_to :user
99
+ end
100
+ ```
101
+
14
102
  #Rails(TestsController)
15
103
  ```rails
16
104
  class Api::V1::TestsController < ApplicationController
17
105
  def create
18
106
  @test = Test.new(test_params)
19
- @user = current_api_v1_user
107
+ @test.user_id = current_api_v1_user.id
20
- @test.user_id = @user.id
21
108
  if @test.save
22
109
  render json: { status: 200, data: test }
23
110
  else
@@ -30,167 +117,4 @@
30
117
  params.require(:test).permit(:title, :image, :body)
31
118
  end
32
119
  end
33
- ```
34
-
35
- #React(CreateTest.tsx)
36
- ```react
37
- import React, { useState, useContext, useEffect } from "react"
38
- import { useHistory } from "react-router-dom"
39
- import { AuthContext } from "App"
40
-
41
- import { makeStyles, Theme } from "@material-ui/core/styles"
42
- import TextField from "@material-ui/core/TextField"
43
- import Card from "@material-ui/core/Card"
44
- import CardContent from "@material-ui/core/CardContent"
45
- import CardHeader from "@material-ui/core/CardHeader"
46
- import Button from "@material-ui/core/Button"
47
-
48
- import { createTest } from "lib/api/test"
49
- import { CreateTestParams } from "interfaces/index"
50
-
51
- const useStyles = makeStyles((theme: Theme) => ({
52
- container: {
53
- marginTop: theme.spacing(6)
54
- },
55
- submitBtn: {
56
- marginTop: theme.spacing(2),
57
- flexGrow: 1,
58
- textTransform: "none"
59
- },
60
- header: {
61
- textAlign: "center"
62
- },
63
- card: {
64
- padding: theme.spacing(2),
65
- maxWidth: 400
66
- }
67
- }))
68
-
69
- const CreateTest: React.FC = () => {
70
- const { isSignedIn, currentUser } = useContext(AuthContext)
71
- const classes = useStyles()
72
- const histroy = useHistory()
73
-
74
- const [title, setTitle] = useState<string>("")
75
- const [image, setImage] = useState<string>("")
76
- const [body, setBody] = useState<string>("")
77
-
78
- const handleSubmit = async (e: React.MouseEvent<HTMLButtonElement>) => {
79
- e.preventDefault()
80
-
81
- const params: CreateTestParams = {
82
- title: title,
83
- image: image,
84
- body: body
85
- }
86
-
87
- try {
88
- const res = await createTest(params)
89
- console.log(res)
90
- if (res.status === 200) {
91
- console.log("登録完了")
92
- histroy.push("/mypage")
93
- } else {
94
- setAlertMessageOpen(true)
95
- }
96
- } catch (err) {
97
- console.log(err)
98
- setAlertMessageOpen(true)
99
- }
100
- }
101
-
102
- return (
103
- <>
104
- {
105
- isSignedIn && currentUser ? (
106
- <form noValidate autoComplete="off">
107
- <Card className={classes.card}>
108
- <CardHeader className={classes.header} title="Sign Up" />
109
- <CardContent>
110
- <TextField
111
- variant="outlined"
112
- required
113
- fullWidth
114
- label="title"
115
- value={title}
116
- margin="dense"
117
- onChange={event => setTitle(event.target.value)}
118
- />
119
-
120
- <input
121
- type="file"
122
- value={image}
123
- onChange={event => setImage(event.target.value)}
124
- >
125
- </input>
126
-
127
- <TextField
128
- variant="outlined"
129
- required
130
- fullWidth
131
- label="body"
132
- value={body}
133
- margin="dense"
134
- onChange={event => setBody(event.target.value)}
135
- />
136
-
137
- <Button
138
- type="submit"
139
- variant="contained"
140
- size="large"
141
- fullWidth
142
- color="default"
143
- disabled={!title || !body ? true : false}
144
- className={classes.submitBtn}
145
- onClick={handleSubmit}
146
- >
147
- 登録
148
- </Button>
149
- </CardContent>
150
- </Card>
151
- </form>
152
- ) : (
153
- <h1>Not signed in</h1>
154
- )
155
- }
156
- </>
157
- )
158
- }
159
-
160
- export default CreateTest
161
- ```
162
-
163
- #client.ts
164
- ```react
165
- import applyCaseMiddleware from "axios-case-converter"
166
- import axios from "axios"
167
-
168
- const options = {
169
- ignoreHeaders: true
170
- }
171
-
172
- const client = applyCaseMiddleware(axios.create({
173
- baseURL: "http://localhost:3001/api/v1"
174
- }), options)
175
-
176
- export default client
177
- ```
178
-
179
- #test.ts
180
- ```react
181
- import client from "lib/api/client"
182
- import { CreateTestParams } from "interfaces/index"
183
-
184
- export const createTest = (params: CreateTestParams) => {
185
- return client.post("/tests", params)
186
- }
187
- ```
188
-
189
- #interfaces/index.ts
190
- ```react
191
- export interface CreateTestParams {
192
- title: string
193
- image?: string
194
- body: string
195
- }
196
120
  ```

1

2021/07/04 20:05

投稿

aaa11
aaa11

スコア14

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