0

私は最初から認証システムを持っています。ユーザーが「プロファイルの編集」をクリックすると、編集するフィールドに関係なく、現在のパスワードを入力する必要があります。

def update
  if params[:user][:password].present?
    authenticated = @user.authenticate(params[:user][:current_password])
    if authenticated && @user.update(user_params)
      redirect_to root_url
      flash[:notice] = "Your profile was successfully updated!"
    else
      @user.errors.add(:current_password, 'is invalid') unless authenticated
      render :edit
    end
  elsif @user.update(user_params)
    redirect_to root_url
    flash[:notice] = "Your profile was successfully updated!"
  else
    render :edit
  end
end

ユーザーがパスワードを変更したい場合にのみ、認証を呼び出すか、コンテキスト モデルの検証を使用するにはどうすればよいですか?

4

2 に答える 2

1

このロジックをモデルに混在させることはお勧めしません。アプリケーションが時間の経過とともに成長するにつれて、従うのが困難な複雑さになるからです。

フォームオブジェクトを調べてみてください:

私は次のようなものを実装します:

class UserUpdateForm
  include ActiveModel::Model

  # Attributes
  attr_accessor :user, :new_password, :new_password_confirmation

  # Validations
  validates :current_password, if: :new_password
  validate :authenticate, if: :current_password
  validates :new_password, confirmation: true, allow_blank: true

  def initialize(user)
    self.user = user
  end

  def submit(params)
    self.new_password = params[:new_password]
    self.new_password_confirmation = params[:new_password_confirmation]

    if self.valid?
      # Set other attributes as needed, then set new password below.
      self.user.password = self.new_password if self.new_password.present?
      self.user.save
    else
      false
    end
  end

private

  def authenticate
    unless self.authenticate(self.current_password)
      self.errors.add(:current_password, 'is invalid')
    end
  end
end

次に、コントローラーから次のように呼び出すことができます。

def update
  @user_update_form = UserUpdateForm.new(@user)

  if @user_update_form.submit(params)
    flash[:notice] = "Your profile was successfully updated!"
    redirect_to root_url
  else
    render :edit
  end
end

ビューの処理方法などについては、上記のリンクを参照してください。これは、開始するためのものです。

于 2015-05-20T15:47:29.120 に答える
0

このアクション ステートメントでネストされた if-else を作成して、オブジェクト内のnew_passwordand new_password_confirmation(または、新しいパスワードおよび確認フィールドが呼び出されたもの) の存在を確認することができparams[:user]ます。それらが存在する場合 - 既存のパスワードを入力するように要求して、ページのキングにリダイレクトできます。

もう 1 つの方法は、ajax を使用して、同じ要求でダイアログ ボックスを非同期的に表示することです (これを処理する、respond_with 自己呼び出し JavaScript 関数など)。次に、コントローラーの他のアクションでダイアログの送信ボタンを処理します。

更新(バリデーターの使用を検討):

検証を考慮して、独自のバリデーター(パスワード用) と条件を作成して、新しいパスワードフィールドにクライアントからのデータがいつ来るかを確認することができます。

次のようになると思います。

validate :password_update?

def password_update?
    if new_password.present?
        if current_password !== self.password
          errors.add(:current_password, "must be supplied!")
        else
            # update data and password
        end
    else
        # do your regular update
    end
end
于 2015-05-20T15:26:52.823 に答える