2011-07-01 133 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