我正在制作一个自定义密码编辑表单,我只更改密码。下面是我的用户控制器的代码:
def change_my_password
@user = User.find(current_user.id)
end
def update_my_password
@user = User.find(current_user.id)
#raise @user.inspect
if @user.update_with_password(params[:user])
sign_in @user, :bypass => true
redirect_to users_path, :notice => "Password updated."
else
sign_in @user, :bypass => true
render action: "change_my_password", :alert => "Unable to update user."
end
end
这是我的用户模型
class User < ActiveRecord::Base
rolify
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable,
# :lockable, :timeoutable and :omniauthable, :registerable,
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
# Setup accessible (or protected) attributes for your model
attr_accessible :role_ids, :password, :password_confirmation, :username, :name, :email, :as => :admin
attr_accessible :password, :password_confirmation, :username, :name, :email, :remember_me
#attr_protected :username, :name, :email, :remember_me, :password, :password_confirmation
validates_uniqueness_of :username
validates_presence_of :username, :email
validates_uniqueness_of :email
end
这是我的修改密码表单
= simple_form_for(@user, :url=>update_my_password_user_path(@user), :html => { :method => :put, :class => 'form-vertical' }) do |f|
= f.error_notification
= display_base_errors @user
= f.input :password, :autocomplete => "off", :required => true
= f.input :password_confirmation, :required => true
= f.input :current_password, :hint => "we need your current password to confirm your changes", :required => true
= f.button :submit, 'Update', :class => 'btn-primary'
= link_to "Back", :back
这一切似乎都很好,但发生的事情是-如果我输入一个错误的密码确认,然后我提示错误,但是当我再次提交表单时,我退出了,密码没有改变。从日志来看,当我第一次提交表单更改密码时,密码确认错误,它就会将我注销。我不明白我在哪里走错了-我甚至把sign_in用户,以避免不得不签出,但它仍然不工作。我哪里做错了?
在路由和视图中使用post
方法代替put
-
路线。rb -
resources "users" do
collection do
get 'change_my_password'
post 'update_my_password'
end
end
change_my_password.html。erb -
<%= form_for(@user, :url => { :action => "update_my_password" }, :html => {:method => "post"}) do |f| %>
<%= f.text_field :password, :autocomplete => "off", :required => true %>
<%= f.text_field :password_confirmation, :required => true %>
<%= f.text_field :current_password, :hint => "we need your current password to confirm your changes", :required => true %>
<%= f.submit 'Update', :class => 'btn-primary' %>
<%= link_to "Back", :back %>
<% end %>
这对我来说没有任何问题。
干杯!