2011-07-01 136 views
29

我有一個自定義控制器,可以根據代碼here處理用戶密碼的編輯。設計不驗證密碼/密碼確認

用戶模型

attr_accessible :password, :password_confirmation, :username, :login 
... 
devise :database_authenticatable, 
     :lockable, 
     :registerable, 
     :recoverable, 
     :rememberable, 
     :trackable 

PasswordsController

expose(:user) { current_user } 

def update 
    if user.update_with_password(params[:user]) 
    sign_in(user, :bypass => true) 
    flash[:notice] = "success" 
    else 
    render :edit 
    end 
end 

我改密碼錶單位於here

問題是無論我輸入什麼(或不輸入該事項)到編輯密碼錶單中,都會顯示「成功」閃存方法。

+0

是否所有的工作,但它應該如何?如果確認字段不匹配或者current_password錯誤,它不會更改密碼? – Dex

+0

它仍會將其更改爲:無論密碼如何(如果有的話)都在:password_confirmation中。 –

+0

如果將if語句更改爲'if params [:user] [:password] == params [:user] [:password_confirmation]'並將'user.update_with_password(params [:user])''更改爲body ? –

回答

62

如果你想設計驗證,你需要添加:validatable模塊到你的模型。這是很容易做到的,只是添加:validatabledevise調用模塊列表,所以你的模型說:

devise 
    :database_authenticatable, 
    :lockable, 
    :registerable, 
    :recoverable, 
    :rememberable, 
    :trackable, 
    :validatable 

這將使色器件添加驗證。

另一個簡單的方法是添加自己的驗證。如果你只是想驗證密碼確認相匹配,您可以通過添加這對您的模型添加validates_confirmation_of驗證:

validates_confirmation_of :password 

我希望這有助於。

+1

'validates_confirmation_of:password'是我失蹤 –

1

在控制器中找到更新對象。

user = User.find_by_id(params[:id]) 
    unless user.blank? 
     if user.update_attributes(params[:user]) 
     flash[:notice] = "User updated successfully." 
     redirect_to "somwhere" 
     else 
     render :action => 'edit' 
     end 
    else 
     render :action => 'edit' 
    end 

,如果你不想更新舊密碼,然後更新用之前添加這些行,以便新的代碼將是:在user.rb模型

user = User.find_by_id(params[:id]) 
     unless user.blank? 
      params[:user].delete(:password) if params[:user][:password].blank? 
      params[:user].delete(:password_confirmation) if params[:user][:password_confirmation].blank? 
if user.update_attributes(params[:user]) 
      flash[:notice] = "User updated successfully." 
      redirect_to "somwhere" 
      else 
      render :action => 'edit' 
      end 
     else 
      render :action => 'edit' 
     end 

寫的財產以後這樣

devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable, :locakable 
4

我想你忘記了在軌4

before_action application_controller.rb初始化參數強:configure_permitted_pa​​rameters,如果:devise_controller? 保護

def configure_permitted_parameters  
    devise_parameter_sanitizer.for(:sign_up){|u|u.permit(:email,:password,:password_confirmation)} 
end 
+1

這就是我的一點,我忘了將'password_confirmation'添加到清理過的參數列表,謝謝! – hernandes