LoginSignup
0
0

Rails バリデーションの使い方と種類について(ActiveRecord型)。知らないとやばいくらい基本❗️

Last updated at Posted at 2021-07-24

バリデーションとは

データを保存する,不正なデータがデータベースに保存されないようにデータをチェックするシステムです。自分は共同開発の時にはログインなどの認証機能を作った時にバリデーションをかけずに、プルリクエストを出してボコボコにされてしまったことがあります。そのくらいセキュリティ上でも大切です。

なぜバリデーションを使うのか.

正しいデータだけをデータベースに保存するために使われます。

使い方

基本的にRailsでもLaravelでもモデルでバリデーションを使うのが多いみたいです。
Railsチュートリアルではモデルに書いてました。

validates :カラム名(シンボル指定),検証ルール(シンボル指定)

validationの種類

presence: true カラムの値が存在するかチェック
以下のようにcontent(テキスト内容)が存在するかのチェックです。

post.rb
class Post < ApplicationRecord
  validates :content, presence: true
end

複数のバリデーションルールを指定する場合、以下のように書くこともあります。

post.rb
class Post < ApplicationRecord
  validates :content, presence: true, length: { maximum: 140 }
end

inclusion: { in: [true, false] } boolean属性が空でないこと

user.rb
class User < ApplicationRecord
  validates :birthplace, inclusion: { in: [true, false] }
end

{acceptance: true}チェックボックス

class User < ApplicationRecord
  validates :actor, acceptance: true
end

文字数の指定 
lengthを使って{maximum:数値}を指定して最大文字数を{minimum:数値}を指定して
最小文字列を指定inを使い範囲や文字数飲みのバリデーションをかけ、
isで指定した数字のみ。

class Post < ApplicationRecord

validates :content, {length: {maximum:100} } #最大100文字以下

validates :content, {length: {minimun:30} } #30文字以上

validates :content, {length: {in: 10..80} }  #10文字以上80文字以下

validates :content, {length: {is: 30 }} #30文字のみ

end

資料

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