26
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

モデルにパスワード属性を追加する方法

Last updated at Posted at 2014-05-03

自分向けのメモ

Gemfileのbcryptを有効にする。

wikipedia BCrypt

gem 'bcrypt', '~> 3.1.7' # rails4.0.0のGemfileの場合

modelにpassword_digest属性を追加する

モデルを新規作成の場合

rails g scaffold account email:string password_digest:string

modelにhas_scure_passwordを指定する

参考:Rails API Doc:has_secure_password

has_secure_passwordによって、以下が行われる。

  • モデルにpassword,password_confirmation属性の追加
  • password,password_confirmationのvalidationの追加
  • authoricateメソッドの追加
#account.rb
class Account < ActiveRecord::Base
  has_secure_password
end

controllerのstrong parameterの編集

password, password_confirmationを追加。password_digestを削除。

def account_params
  params.require(:account).permit(:name, :display_name, :password, :password_confirmation, :email)
end  

view formの編集

password_digestのフィールドを削除して、passwordとpassword_confirmationに置き換える。

# 変更前
= f.label :password_digest
= f.text_field :password_digest
# 変更後
= f.label :password
= f.password_field: password
= f.label :password_confirmation
= f.password_field: password_confirmation

コントローラでの検証方法

  def create
    account = Account.find_by(name: user_params[:name])
    if account and account.authenticate(account_params[:password])
      # login.
    else
      #error.
    end
  end

参考

has_secure_passwordを読む
has_secure_passwordによるユーザ認証

26
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?