Search code examples
mysqlruby-on-railsdatabaseruby-on-rails-4devise

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

  • How do you validate email? You could use a custom method to decrypt it before validate against (for e.g.) a regex. Alternatively, you can use ActiveRecord Callbacks. In your case, after_validation can be useful :)

    after_validation(on: :create) do
      self.email= AESCrypt.encrypt(email, "password")
    end