質問編集履歴
1
現在のコード追加
title
CHANGED
File without changes
|
body
CHANGED
@@ -16,4 +16,92 @@
|
|
16
16
|
|
17
17
|
↓に同じ状況での対処方法がありましたが、2013年と古い記事でしたので
|
18
18
|
今は違う方法が一般的でしたら教えていただけると幸いです。
|
19
|
-
[Railsで「このタイミングだけこのバリデーションしたい」っていうとき](http://ria10.hatenablog.com/entry/20130617/1371483318)
|
19
|
+
[Railsで「このタイミングだけこのバリデーションしたい」っていうとき](http://ria10.hatenablog.com/entry/20130617/1371483318)
|
20
|
+
|
21
|
+
|
22
|
+
※以下から補足追加
|
23
|
+
パスワードの登録は、チュートリアルを真似して
|
24
|
+
以下のようにしてます。
|
25
|
+
|
26
|
+
Userモデル
|
27
|
+
```ruby
|
28
|
+
class User < ApplicationRecord
|
29
|
+
|
30
|
+
has_secure_password
|
31
|
+
validates :password,
|
32
|
+
presence: true,
|
33
|
+
allow_nil: true,
|
34
|
+
length: { in: 8..30 }
|
35
|
+
|
36
|
+
|
37
|
+
validates :password_digest,
|
38
|
+
presence: true,
|
39
|
+
length: { maximum: 100 }
|
40
|
+
end
|
41
|
+
|
42
|
+
```
|
43
|
+
|
44
|
+
Userコントローラ
|
45
|
+
```ruby
|
46
|
+
class UsersController < LoginController
|
47
|
+
before_action :logged_in_user, only: [:edit, :update]
|
48
|
+
before_action :correct_user, only: [:edit, :update]
|
49
|
+
|
50
|
+
def edit
|
51
|
+
@user = User.find(params[:id])
|
52
|
+
end
|
53
|
+
|
54
|
+
def update
|
55
|
+
@user = User.find(params[:id])
|
56
|
+
if @user.update_attributes(user_params)
|
57
|
+
flash[:success] = "更新しました"
|
58
|
+
redirect_to @user
|
59
|
+
else
|
60
|
+
render 'edit'
|
61
|
+
end
|
62
|
+
end
|
63
|
+
|
64
|
+
|
65
|
+
|
66
|
+
private
|
67
|
+
|
68
|
+
def user_params
|
69
|
+
params.require(:user).permit(:name, :email, :password, :password_confirmation)
|
70
|
+
end
|
71
|
+
|
72
|
+
|
73
|
+
end
|
74
|
+
|
75
|
+
```
|
76
|
+
|
77
|
+
パスワード変更コントローラ
|
78
|
+
```ruby
|
79
|
+
class PasswordEditsController < LoginController
|
80
|
+
before_action :logged_in_user, only: [:edit, :update]
|
81
|
+
before_action :correct_user, only: [:edit, :update]
|
82
|
+
|
83
|
+
def edit
|
84
|
+
@user = User.find(params[:id])
|
85
|
+
end
|
86
|
+
|
87
|
+
def update
|
88
|
+
@user = User.find(params[:id])
|
89
|
+
if @user.update_attributes(user_params)
|
90
|
+
flash[:success] = "更新しました"
|
91
|
+
redirect_to edit_password_edit_path
|
92
|
+
else
|
93
|
+
render 'edit'
|
94
|
+
end
|
95
|
+
end
|
96
|
+
|
97
|
+
|
98
|
+
|
99
|
+
private
|
100
|
+
|
101
|
+
def user_params
|
102
|
+
params.require(:user).permit(:password, :password_confirmation)
|
103
|
+
end
|
104
|
+
|
105
|
+
end
|
106
|
+
|
107
|
+
```
|