When implementing a process such as updating and saving a user's profile information, I want to enter only the information that the user wants to change and skip other form variation checks (especially passwords)! I think there are scenes like that. This time I will show you how to do it.
Use the : on option
in the validation options. For example, by setting on :: create
, the validation check can be performed only when a new record is created.
In my case, the validation check was also performed on the terms of use and the personal information check (accepted column), so this validation check was activated even during the update action, and the user information could not be changed. I did. This can be avoided by using the : on option
to perform the validation check only when a new user is registered.
user.rb
validates :password, presence: true, length: { minimum: 6 }, on: :create
validates :accepted, acceptance: { message: 'Please check' }, on: :create
You can specify the action like this.
You can also define a custom context with the : on option
!
For more information, see This item in the Rails Guide.
You can also do the same with a password by setting allow_nil: true
.
This is an option that does not validate if the value is nil.
e? If I specify this, will an empty password be saved? ?? I think that has_secure_password is used to verify the existence when the object is created (mostly gem'bcrypt' is used), so an empty password will not be saved in the DB. There is none.
So, nicely, you can skip validation only when you execute the update action.
This is a personal development and the scale is still small, but I felt that casual validation changes would have a big impact on the app for large services. .. ** Validation should not be defined globally, but should be limited as much as possible to reduce the range of influence **!
I output what I learned every day! If you have any suggestions, I would appreciate it if you could comment.