我的建议是使用表单对象:
应用程序/表格/change_password_form.rb
class ChangePasswordForm
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
# Add all validations you need
validates_presence_of :old_password, :password, :password_confirmation
validates_confirmation_of :password
validate :verify_old_password
attr_accessor :old_password, :password, :password_confirmation
def initialize(user)
@user = user
end
def submit(params)
self.old_password = params[:old_pasword]
self.password = params[:password]
self.password_confirmation = params[:password_confirmation]
if valid?
@user.password = password
@user.password_confirmation = password_confirmation
@user.save!
true
else
false
end
end
def verify_old_password
self.errors << "Not valid" if @user.password != password
end
# This method is required
def persisted?
false
end
end
在控制器中初始化表单对象@pass_form = ChangePasswordForm.new(current_user)
并在您的模式中使用该对象:form_for @pass_form...
并添加old_password
,password
和password_confirmation
字段。
最后,例如,在更新操作中:
@pass_form = ChangePasswordForm.new(current_user)
if @pass_form.submit(params[:change_password_form])
redirect_to some_path
else
render 'new'
end
我没有测试过这段代码,但你明白了。看看这个Railscasts。