0

Rails を使用して作成したユーザーモデルがあります ( Rails チュートリアル Bookhas_secure_passwordに基づく):

スキーマ.rb:

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

ユーザー.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:

def update 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

終わり

4

1 に答える 1

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

それは私にとってはうまくいくようでした。お役に立てば幸いです。

于 2013-01-16T15:13:47.280 に答える