'How to Encrypt data after validation in Ruby on Rails?
I am using devise for authentication, register. Now i want to save emailId in MySQL in encrypted format. So i use gem 'aescrypt'.
My controller:
def create
@dashboard_user = DashboardUser.new(dashboard_user_params)
@dashboard_user.created_by=current_dashboard_user.username
@dashboard_user.company_id=current_dashboard_user.company_id
active_ind = ""
email = @dashboard_user.email
if params["active"] == nil then
active_ind = "0"
else
active_ind = "1"
end
@dashboard_user.active = active_ind
@dashboard_user.email= AESCrypt.encrypt(email, "password")
respond_to do |format|
if @dashboard_user.save
format.html { flash[:notice] = 'User successfully Created.' and redirect_to action: "index"}
else
@dashboard_user.email = email
format.html { render :new }
end
end
end
When i try to save user, it throws Email invalid. I removed validation for email in model. Even though same error exists. What problem it is? If there any way to encrypt data after validation?
Thanks in advance.
Solution 1:[1]
You can encrypt the data using using a method triggered by the after_validation callback. It is described here: http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html
Solution 2:[2]
On its model you can just declare like the example scenario below: E.g.:
after_validation :encrypt_cc_number, on: :create
It will validate then encrypt the credit car number on a create action.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | davidb |
| Solution 2 | Raphael Onofre |
