ユーザーのモデルを作成

6.1 Userモデル

User のデーターを作成する場所がないのでデータ構造を作成する
データー構造 =モデル

データーを長期的に保存する場所をデータベースという
データベースとのやり取りをするライブラリーをActive Record
Active Recordはデータ検索/作成/保存を持っている

6.1.1 データーベースの移行

永続性を持ったユーザーモデルを構築する

rails g model User name:string email:string 

マイグレーションファイル作成

class CreateUsers < ActiveRecord::Migration[6.0]
 def change
   create_table :users do |t|
     t.string :name
     t.string :email

     t.timestamps
   end
 end
end

マイグレーションを実行

rails db:migrate

6.1.2 モデルファイル

マイグレーションが実行されモデルファイルもできた

class User < ApplicationRecord
end

UserはApplcationRecordを継承しているので、必然的にApplicationRecord::Baseを継承している。

6.13 ユーザーオブジェクトを作成

モデルを調べるためにコンソールを開く

Rails c --sandbox

sandboxはデーターベースに影響しない

有効性を調べるメソッド

User.valid?

データーベースに格納する

User.save
User.create

格納されたデーターを削除

User.destroy

ユーザーオブジェクトを検索する

存在しているユーザを検索

User.find(1)

ユーザーが存在しない場合は例外が発生。

特定の属性で検索

User.find_by(emall "aioeo@yahoo.co.jp")

最初のユーザを検索

User.first

すべてのユーザー検索

User.all

AcitiveRecord::Relationはクラスをまとめてくれる

6.1.5 ユーザーオブジェクトを更新

オブジェクトを更新

属性を個別で代入

user
user.emall= "aioeo@sample.com"
user.save

マジックカラムも更新

user.created_at
user.update_at

updateを使って更新

user.update(name:"aiueo", email: "aioeo@sample.com")
user.name
user.emall

6.2 ユーザーを検証

nameとemailにたくさんの文字列をいれない
Active Recordで検証を行う
駆動開発テストをバリデーションと行う

6.2.1 有効性を検証

require "test_helper"
class User < AcitiviSupport::TestCase
  def setup
  @user = User.new(name:"Example User", email:"user@example.com")
  end
  test "should be valid" do
   assert @user.valid?
 end
end



6.2.2 存在性を検証

属性が存在しているかを検証する

require "test_helper"
class User < AcitiviSupport::TestCase
  def setup
  @user = User.new(name:"Example User", email:"user@example.com")
  end
  test "should be valid" do
   assert @user.valid?
 end
  test "name should be present" do
    @user.name = ""
    assert.not@user.valid?
end

6.2.3 長さを検証

maximumパラメータを用いてlengthを使う

class User < ApplicationRecord
  validates :name, presence :true, length:{maximum:50}
  validates :email, presence :true, length:{maximum:50}

6.2.4 フォーマットを検証

正規表現を利用しフォーマットを制限

class User < ApplicationRecord
 validates :name,  presence: true, length: { maximum: 50 }
 VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
 validates :email, presence: true, length: { maximum: 255 },
                   format: { with: VALID_EMAIL_REGEX }
end

6.25 一意性を検証


6.3 セキュアなパスワード

ハッシュ化しデーターベースに登録
ハッシュ化関数を使って不可逆的データにする

6.3.1 ハッシュ化されたパスワード

has_secure_passwordを使用し機能を使う
・データーベースのpassword_digestに保存
・仮想的な属性やバリデーションを使える
・autehentcateメソッドが使える

add_password_digest_to_usersというマイグレーションファイルを作成

rails g migration add_password_digest_to_users password_digest:string

6.3.2 ユーザーがセキュアなパスワードを持っている

パスワードとパスワード確認を入れる

6.3.3 パスワードの最小文字数を入れる

@user.password = @user.password_confirmation = "a" * 5

この記事が気に入ったらサポートをしてみませんか?