【问题标题】:ROR: undefined method `authenticate'ROR:未定义的方法“验证”
【发布时间】:2012-10-31 05:33:12
【问题描述】:

我想在我的 Rails 应用程序中添加“更改密码”功能,我从这里研究它 (207.44.138.58/~roreexper/viewtopic.php?t=690&highlight=&sid=16f7417dcbb3cb8960912c8134351fd9)

在我的视图页面中我添加:-

 = form_tag :action => 'update' do
   - flash.each do |key, value|
     %div.TxtRed{:class => "flash #{key}"}= value
   %p
     %label Current password
     %br
     = password_field_tag "user[current_password]", nil
   %p
     %label New password
     %br
     = password_field_tag "user[password]", nil
   %p
     %label Confirm password
     %br
     = password_field_tag "user[password_confirmation]", nil
   %P
     = button_tag "Save", :class => "btn-custom ML10", :type => :submit

在控制器中:-

  def update
    return unless request.post?
    @user = Refinery::User.find_by_id(current_user.id)
    if current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password])

       if (params[:user][:password] == params[:user][:password_confirmation])

          current_user.encrypted_password = crypted_password(params[:user] [:password] ,current_user.salt)

          flash[:notice] = current_user.save ?"Password changed" :"Password not changed"
          redirect_to my_page_path

       else

          flash[:notice] = "Password mismatch"
          @current_password = params[:current_password]

       end

    else

       flash[:notice] = "Wrong password"

    end
 end

 def crypted_password(password, salt)
   string_to_hash = password + "nyros" + salt
   Digest::SHA1.hexdigest(string_to_hash)
 end

但它不能正常工作并给出错误: "# 的未定义方法 `authenticate'"

【问题讨论】:

    标签: ruby-on-rails-3.2 change-password


    【解决方案1】:

    如果调用它的对象为 nil,则 authenticate 方法将引发异常。换句话说,当find_by 没有找到匹配的用户时。

    if 结构的条件下测试@user 不为nil,而不是在if 条件下调用authenticate 方法。所以改变:

    @user = Refinery::User.find_by_id(current_user.id)
    if !@user.nil?
        current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password])
    .
    .
    .
    

    @user = Refinery::User.find_by_id(current_user.id)
    current_user = Refinery::User.authenticate(@user.username, params[:user][:current_password])
    

    【讨论】:

    • 这并不能解决他遇到的错误。 authenticate 仍然是未定义的。
    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多