在我的更新用户配置文件表单中,第一个字段要求用户输入她当前的密码。当她提交表格时,我会先验证密码,然后再接受其他字段中的更改。下面是我当前如何做这在用户控制器:要求用户输入密码才能更新配置文件
def update
@user = User.find(params[:id])
if @user.has_password?(params[:user][:password])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to @user
else
render 'edit'
end
else
flash[:failure] = "Password does not match!"
render 'edit'
end
end
我觉得有一个更好的方式来做到这一点。例如,我可以使密码匹配用户模型中的验证。然后formtastic会自动处理我的错误信息(而不是我上面的丑陋闪光方法)。我试着用
validate :password_match?, :on => :update
而且
def password_match?
has_password(params[:user][:password])
end
这样做,但被怀疑params为不从模型访问。
我搜索了20分钟的方法来做到这一点,找不到任何不涉及设计或Authlogic。我从头开始进行身份验证(一切工作正常:登录,会话等)。
请给我看看更好的方式!
如果你使用[色器件(https://github.com/plataformatec/devise),这将是建立在你的[编辑用户注册视图(https://开头github上。 com/plataformatec/devise/blob/master/app/views/devise/registrations/edit.html.erb#L15) – Zabba 2011-04-28 18:18:40
下一次我会确定使用devise。我最近学习了Rails,并参与了一个涉及从头开始构建认证的教程。自那以后,我一直在为我的项目编写代码。 – 2011-04-28 18:22:49