ActiveRecordのattributeメソッド

2017-12-08#rails

class User
  attribute :unencrypted_password, :string
end

例:パスワードのvalidation

パスワードのvalidationを実装する場合を考える。パスワードのvalidationというのは、暗号化される前の値に対して行われる。生パスワードはDBに保存しないが、アクセサがあると便利なのでattributeメソッドで追加する。attributeメソッドで追加した仮想的なカラムにはvalidationが使える。

class User
  attribute :unencrypted_password, :string
 
  before_save :encrypt_password, if: unencrypted_password_changed?
 
  validates :unencrypted_password,
    format: { with: /\A[0-9a-zA-Z]\z/ },
    length: { minimum: 8, maximum: 36 },
    presence: true
 
  private
 
  def encrypt_password
    cost = BCrypt::Engine.cost
    self.password = BCrypt::Password.create(unencrypted_password, cost)
  end
end