在我的更新用戶配置文件表單中,第一個字段要求用戶輸入她當前的密碼。當她提交表格時,我會先驗證密碼,然後再接受其他字段中的更改。下面是我當前如何做這在用戶控制器:要求用戶輸入密碼才能更新配置文件
def update
@user = User.find(params[:id])
if @user.has_password?(params[:user][:password])
if @user.update_attributes(params[:user])
flash[:success] = "Profile updated."
redirect_to @user
else
render 'edit'
end
else
flash[:failure] = "Password does not match!"
render 'edit'
end
end
我覺得有一個更好的方式來做到這一點。例如,我可以使密碼匹配用戶模型中的驗證。然後formtastic會自動處理我的錯誤信息(而不是我上面的醜陋閃光方法)。我試着用
validate :password_match?, :on => :update
而且
def password_match?
has_password(params[:user][:password])
end
這樣做,但被懷疑params爲不從模型訪問。
我搜索了20分鐘的方法來做到這一點,找不到任何不涉及設計或Authlogic。我從頭開始進行身份驗證(一切工作正常:登錄,會話等)。
請給我看看更好的方式!
如果你使用[色器件(https://github.com/plataformatec/devise),這將是建立在你的[編輯用戶註冊視圖(https://開頭github上。 com/plataformatec/devise/blob/master/app/views/devise/registrations/edit.html.erb#L15) – Zabba 2011-04-28 18:18:40
下一次我會確定使用devise。我最近學習了Rails,並參與了一個涉及從頭開始構建認證的教程。自那以後,我一直在爲我的項目編寫代碼。 – 2011-04-28 18:22:49