2017-10-11 72 views
1

我需要在密碼重置操作期間跳過郵政編碼驗證。我到目前爲止所寫的內容如下。重置密碼 - 跳過驗證

User.rb

attr_accessor :email_confirmation, :user_role, :unit_user_property, 
      :skip_validation, :skip_zip_validation, :login 

validates_format_of :zip, 
        with: /\A\d{5}-\d{4}|\A\d{5}\z/, 
        message: 'should be of the format 12345 or 12345-1234', 
        unless: :skip_zipcode_validation? 

# Return true/false to validate zipcode 
# Skips validation if this returns true 
def skip_zipcode_validation? 
    skip_validation.present? || skip_zip_validation.present? 
end 

application_controller.rb

before_action :configure_permitted_parameters, if: :devise_controller? 

protected 



    def configure_permitted_parameters 
    added_attrs = [:phone, :email, :password, :password_confirmation, :remember_me, :skip_zip_validation] 

    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(added_attrs) } 
    devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(added_attrs) } 
    devise_parameter_sanitizer.for(:account_update) { |u| u.permit(added_attrs) } 
    end 

應用程序/視圖/設計/密碼/ edit.html.erb

<%= f.hidden_field :skip_zip_validation, value: true %> 

,但我仍然得到密碼重置時的郵編驗證錯誤。 在調試時,屬性skip_zip_validation顯示爲零。它看起來像屬性沒有得到分配給用戶

任何想法如何解決這個問題?

回答

0

通過重寫設計reset_password_by_token方法來解決這個問題。

def self.reset_password_by_token(attributes={}) 
    original_token  = attributes[:reset_password_token] 
    reset_password_token = Devise.token_generator.digest(self, :reset_password_token, original_token) 

    recoverable = find_or_initialize_with_error_by(:reset_password_token, reset_password_token) 
    recoverable.skip_zip_validation = true 
    if recoverable.persisted? 
     if recoverable.reset_password_period_valid? 
     recoverable.reset_password(attributes[:password], attributes[:password_confirmation]) 
     else 
     recoverable.errors.add(:reset_password_token, :expired) 
     end 
    end 

    recoverable.reset_password_token = original_token if 
    recoverable.reset_password_token.present? 
    recoverable 
end 
0

確保:skip_zip_validation作爲允許的參數傳遞。

class ApplicationController < ActionController::Base 
    before_action :configure_permitted_parameters, if: :devise_controller? 

    def configure_permitted_parameters 
    update_attrs = [:password, :password_confirmation, :current_password:, :skip_zip_validation] 
    devise_parameter_sanitizer.permit :account_update, keys: update_attrs 
    end 
end 
+0

我已經添加了。請參閱最新的問題。 – prajeesh

+0

一次調試,屬性skip_zip_validation顯示爲零 – prajeesh