0

如何在rails 3.2中使用确认密码验证密码

我的代码不起作用

你可以告诉我的错误在哪里

我尝试了许多变化来更改控制器中的代码。

密码保存但未验证到密码确认字段和密码字段。

请帮帮我,帮帮我)))

意见

<%= form_for :password, :url => { :action => "change_password" }, :id => @user do |f| %> 
<% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Save", :class => "button blue" %>
<% end %> 

用户控制器

  def change_password
    @page_title = "Changing Zetfon account password"
    @user = current_user
    if request.post?

       @user.password = Digest::SHA1.hexdigest(params[:password][:password]) 
    if @user.save
        redirect_to :action => 'profile'
        flash[:status] = "Your password was changed. Next time you sign in use your new password."
      else
     flash[:status] = _('Your password not changed')
        render :action => "change_password"
      end
    end
  end

用户模型

  validates_confirmation_of :password
  attr_accessible :password_confirmation
  attr_accessor :password
4

2 回答 2

11

将以下行添加到您的模型中

    validates :password, confirmation: true
于 2014-01-31T05:36:50.413 回答
3

简单地使用是否为时已晚has_secure_password?你可以在这个 RailsCast 中了解它:

http://railscasts.com/episodes/270-authentication-in-rails-3-1

我不确定你为什么有if request.post?. 这不是已经由你的路线决定了吗?

根据文档validates_confirmation_of,我认为您可能需要添加:

validates_presence_of :password_confirmation, :if => :password_changed?

这是文档:

http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_confirmation_of

该文档似乎表明您也不需要attr_accessible :password_confirmation

我希望这会有所帮助。

于 2013-01-30T19:56:07.987 回答