質問編集履歴

1

現在のコード追加

2020/05/19 07:20

投稿

pecchan
pecchan

スコア557

test CHANGED
File without changes
test CHANGED
@@ -35,3 +35,179 @@
35
35
  今は違う方法が一般的でしたら教えていただけると幸いです。
36
36
 
37
37
  [Railsで「このタイミングだけこのバリデーションしたい」っていうとき](http://ria10.hatenablog.com/entry/20130617/1371483318)
38
+
39
+
40
+
41
+
42
+
43
+ ※以下から補足追加
44
+
45
+ パスワードの登録は、チュートリアルを真似して
46
+
47
+ 以下のようにしてます。
48
+
49
+
50
+
51
+ Userモデル
52
+
53
+ ```ruby
54
+
55
+ class User < ApplicationRecord
56
+
57
+
58
+
59
+ has_secure_password
60
+
61
+ validates :password,
62
+
63
+ presence: true,
64
+
65
+ allow_nil: true,
66
+
67
+ length: { in: 8..30 }
68
+
69
+
70
+
71
+
72
+
73
+ validates :password_digest,
74
+
75
+ presence: true,
76
+
77
+ length: { maximum: 100 }
78
+
79
+ end
80
+
81
+
82
+
83
+ ```
84
+
85
+
86
+
87
+ Userコントローラ
88
+
89
+ ```ruby
90
+
91
+ class UsersController < LoginController
92
+
93
+ before_action :logged_in_user, only: [:edit, :update]
94
+
95
+ before_action :correct_user, only: [:edit, :update]
96
+
97
+
98
+
99
+ def edit
100
+
101
+ @user = User.find(params[:id])
102
+
103
+ end
104
+
105
+
106
+
107
+ def update
108
+
109
+ @user = User.find(params[:id])
110
+
111
+ if @user.update_attributes(user_params)
112
+
113
+ flash[:success] = "更新しました"
114
+
115
+ redirect_to @user
116
+
117
+ else
118
+
119
+ render 'edit'
120
+
121
+ end
122
+
123
+ end
124
+
125
+
126
+
127
+
128
+
129
+
130
+
131
+ private
132
+
133
+
134
+
135
+ def user_params
136
+
137
+ params.require(:user).permit(:name, :email, :password, :password_confirmation)
138
+
139
+ end
140
+
141
+
142
+
143
+
144
+
145
+ end
146
+
147
+
148
+
149
+ ```
150
+
151
+
152
+
153
+ パスワード変更コントローラ
154
+
155
+ ```ruby
156
+
157
+ class PasswordEditsController < LoginController
158
+
159
+ before_action :logged_in_user, only: [:edit, :update]
160
+
161
+ before_action :correct_user, only: [:edit, :update]
162
+
163
+
164
+
165
+ def edit
166
+
167
+ @user = User.find(params[:id])
168
+
169
+ end
170
+
171
+
172
+
173
+ def update
174
+
175
+ @user = User.find(params[:id])
176
+
177
+ if @user.update_attributes(user_params)
178
+
179
+ flash[:success] = "更新しました"
180
+
181
+ redirect_to edit_password_edit_path
182
+
183
+ else
184
+
185
+ render 'edit'
186
+
187
+ end
188
+
189
+ end
190
+
191
+
192
+
193
+
194
+
195
+
196
+
197
+ private
198
+
199
+
200
+
201
+ def user_params
202
+
203
+ params.require(:user).permit(:password, :password_confirmation)
204
+
205
+ end
206
+
207
+
208
+
209
+ end
210
+
211
+
212
+
213
+ ```