1
0

More than 3 years have passed since last update.

Railsで架空のCafeのHPを作ってみよう!【5日目】『完全一致の正規表現』編

Posted at

概要

基本Railsの記法に則り書いていきます!
1から全ての説明ではなく
その中であれ?どうやるの?と
疑問に思った点や実装に困った箇所を
ピックアップして紹介していきます♩

設定と準備

・Rails
・HTML
・CSS
・Javascript(jQuery)

↑上記の言語とフレームワークを使い
架空(自分で考えたテキトーなもの)のCafeの
HPを作っていこうと思います!

5日目の作業内容:round_pushpin:

・deviseの導入

5日目の躓いた箇所:zap:

「従業員しかログインできないようにバリデーションを
かけたいけどどうしたらいいだろう?」

今回はHPを作っているため
従業員しかログインできないように
パスワードにバリデーションをかけたい!

前提としてdeviseを導入し、userモデルを作成しています。

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :password,
              format: { with: /??/, allow_blank: true }
end

ここのformatの中に書けばいいと思うが
書き方がわからない...。

結論

答えはシンプルで
\Aと\zで囲えばいいだけ!

user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  validates :password,
              format: { with: /\Asample\z/, allow_blank: true }
end

上記でははsampleという文字列を指定しました。

少し見づらいので分けて書くと
最初の / と最後の / はformatの記法です。
それを\Aと\zで囲み、中に任意の文字列や数字を入れればOKです!
例) / \A "任意の文字列や数字" \z /

この方法で従業員しかログインできないように制限をかけることに成功!

1
0
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
1
0