2013-01-16 2 views
0

나는 내가 사용 지어진 사용자 모델이 레일의합니다 (Rails tutorial Book 기준) has_secure_password :다음 암호 변경보기에 current_password 필드를 추가 하시겠습니까?

schema.rb :

create_table "users", :force => true do |t| 
    t.string "password_digest" 
end 

user.rb :

class User < ActiveRecord::Base 
    attr_accessible :name, :email, :avatar, :password, :password_confirmation, :provider, :uid 

    has_secure_password 

    validates :password, presence: true, length: { minimum: 6 } 
    validates :password_confirmation, presence: true 

그리고이 같은 견해를 가지고 있습니다. uses/password_edit.html.erb :

<%= f.label :password %> 
<%= f.password_field :password, "New Password" %> 

<%= f.label :password_confirmation, "Retype Password" %> 
<%= f.password_field :password_confirmation %> 

이제 상단에 :current_password 필드를 추가하고 싶습니다. 문제는 데이터베이스에 password_digest 열만있는 것입니다.

그래서 저는 여기에서 약간 잃어 버렸습니다. current_password이 올바르지 않은 경우에도 양식에서 오류를 발생시키는 방법을 모르겠습니다.

제안 사항?

편집 :

users_controller.html.erb :

데프 업데이트 OLD_PASSWORD =의 PARAMS [: current_password]

if authenticated = User.authenticate(old_password) 
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank? 
    # Use old password if none indicated 
    params[:user][:password] = old_password 
    params[:user][:password_confirmation] = old_password 
    end 
end 

@user = User.find(params[:id]) 
@user.errors.add(:base, "Invalid password") unless authenticated 
@user.updating_password = true if params[:form_name] == "edit_password" 
if authenticated && @user.update_attributes(params[:user]) 
    flash[:success] = "Profile updated" 
    sign_in @user 
    redirect_to @user 
else 
    if params[:form_name] == "edit_password" 
    render 'edit_password' 
    else 
    render 'edit' 
    end 
end 
@user.updating_password = nil 

+0

이제보기가 어떻게 보이는지 추가하고 컨트롤러 편집에서 서식을 수정할 수 있습니까? – Geoff

답변

1

나는 최근 비슷한 일을했다. 내보기에서 모델과 관련이없는 입력을 추가하면 컨트롤러가 다음과 같이 보입니다.

def update 
    old_password = params[:current_password] 

    @user = User.find(params[:id]) 

    if authenticated = @user.authenticate(old_password) 
    if params[:user][:password].blank? && params[:user][:password_confirmation].blank? 
     # Use old password if none indicated 
     params[:user][:password] = old_password 
     params[:user][:password_confirmation] = old_password 
    end 
    end 

    @user.errors.add(:base, "Invalid password") unless authenticated 

    if authenticated && @user.update_attributes(params[:user]) 
    ... 
end 

내게 잘 맞는 것처럼 보였습니다. 나는 그것이 당신을 돕기를 바랍니다.

+0

인증에 실패하면 사용자의 변경 사항이 취소됩니다. 질문자의 연습 문제로 원한다면 그것을 포함 시키도록 수정할 수 있습니다. – Geoff

+0

답변 해 주셔서 감사합니다. 그걸 포함시켜 주시겠습니까? – alexchenco

+1

그래. 필자는 마지막 줄'@ user.assign_attributes (params [: user])'와'@ user.valid? '앞에 다음 두 문장을 추가하면 마지막 줄을'@ user.save'로 변경할 수 있다고 생각합니다. – Geoff

관련 문제