设计 - 更改密码不起作用 - 而是将用户注销

时间:2013-01-16 08:12:25

标签: ruby-on-rails-3 devise

我正在制作一个自定义密码编辑表单,我只更改密码。这是我的用户控制器的代码:

  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用户中放置以避免退出但仍然无法正常工作。我在哪里可能会出错?

1 个答案:

答案 0 :(得分:1)

在路线中使用post方法代替put,并按以下方式查看 -

routes.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 %>

这对我没有任何问题。

干杯!